using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace GmRelay.Web.Services;

public sealed class DiscordAuthService(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<DiscordAuthService> logger)
{
    private readonly DiscordOAuthOptions _options = configuration.GetSection("Discord").Get<DiscordOAuthOptions>() ?? new DiscordOAuthOptions();

    public string BuildAuthorizeUrl(string state)
    {
        _options.Validate();
        var scopes = string.Join(" ", _options.Scopes);
        return $"https://discord.com/oauth2/authorize?client_id={_options.ClientId}&redirect_uri={Uri.EscapeDataString(_options.RedirectUri)}&response_type=code&scope={Uri.EscapeDataString(scopes)}&state={Uri.EscapeDataString(state)}";
    }

    public async Task<DiscordUser?> ExchangeCodeAsync(string code)
    {
        _options.Validate();
        var client = httpClientFactory.CreateClient();

        var tokenResponse = await ExchangeCodeForTokenAsync(client, code);
        if (tokenResponse is null)
            return null;

        return await FetchUserProfileAsync(client, tokenResponse.AccessToken);
    }

    private async Task<DiscordTokenResponse?> ExchangeCodeForTokenAsync(HttpClient client, string code)
    {
        var content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "authorization_code",
            ["code"] = code,
            ["redirect_uri"] = _options.RedirectUri,
            ["client_id"] = _options.ClientId,
            ["client_secret"] = _options.ClientSecret
        });

        var response = await client.PostAsync("https://discord.com/api/oauth2/token", content);
        var json = await response.Content.ReadAsStringAsync();
        if (!response.IsSuccessStatusCode)
        {
            logger.LogError("Discord token exchange failed: {StatusCode} {Body}. client_id={ClientId}, redirect_uri={RedirectUri}",
                (int)response.StatusCode, json, _options.ClientId, _options.RedirectUri);
            return null;
        }

        return JsonSerializer.Deserialize<DiscordTokenResponse>(json);
    }

    private static async Task<DiscordUser?> FetchUserProfileAsync(HttpClient client, string accessToken)
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        var response = await client.GetAsync("https://discord.com/api/users/@me");
        if (!response.IsSuccessStatusCode)
            return null;

        var json = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<DiscordUser>(json);
    }
}

public sealed record DiscordTokenResponse(
    [property: JsonPropertyName("access_token")] string AccessToken,
    [property: JsonPropertyName("token_type")] string TokenType,
    [property: JsonPropertyName("expires_in")] int ExpiresIn,
    [property: JsonPropertyName("scope")] string Scope);

public sealed record DiscordUser(
    [property: JsonPropertyName("id")] string Id,
    [property: JsonPropertyName("username")] string Username,
    [property: JsonPropertyName("discriminator")] string Discriminator,
    [property: JsonPropertyName("avatar")] string? Avatar,
    [property: JsonPropertyName("email")] string? Email)
{
    public string DisplayName =>
        Discriminator == "0" ? Username : $"{Username}#{Discriminator}";

    public string? AvatarUrl =>
        !string.IsNullOrWhiteSpace(Avatar)
            ? $"https://cdn.discordapp.com/avatars/{Id}/{Avatar}.png"
            : null;
}
