using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Lentia.Core.Auth.Yggdrasil;
using Lentia.Core.Constants;
using Lentia.Core.Utils;

namespace Lentia.Core.Auth.OAuth2;

public class Discord {
    
    private static HttpListener? _listener;
    private static readonly string _url = "http://localhost:8877/auth/provider/discord/login/callback/";

    public static async Task<string?> ListenForCode() {
        _listener = new HttpListener();
        _listener.Prefixes.Add(_url);
        _listener.Start();

        HttpListenerContext context = await _listener.GetContextAsync();
        HttpListenerRequest request = context.Request;

        string? code = request.QueryString["code"];
        string redirectUrl = "https://yggdrasil.azures.fr/static/success.html";

        HttpListenerResponse response = context.Response;

        response.StatusCode = (int)HttpStatusCode.Redirect;
        response.RedirectLocation = redirectUrl;
        response.OutputStream.Close();

        _listener.Stop();

        return code;
    }

    public static async Task<AuthResult> LoginWithDiscordOAuth2(string authCode) {
        var url = $"https://yggdrasil.azures.fr/auth/provider/discord/login/callback?code={authCode}&requestUser=true";
        try {
            var response = await HttpHelper.FetchAsync(url, HttpMethod.Get);
            if (response.IsSuccessStatusCode) {
                var data = await response.Content.ReadFromJsonAsync<AuthenticateResponse>();
                return data != null ? AuthResult.Ok(data) : AuthResult.Fail("Erreur de lecture des données.");
            } else {
                var errorData = await response.Content.ReadFromJsonAsync<YggdrasilError>();
                Console.WriteLine(await response.Content.ReadAsStringAsync());
                return AuthResult.Fail(
                    errorData?.errorMessage ?? "Identifiants invalides.",
                    errorData?.error,
                    errorData?.cause
                );
            }
        } catch (Exception ex) {
            throw new Exception($"Error when establishing connection to the API : {ex.Message}");
        }
    }

}