using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Threading.Tasks;
using OpenIddict.Server;
using Microsoft.AspNetCore.Http;

namespace Ablera.Serdica.Authority.OpenIddictServerHandlers;

public sealed class EndSessionHandler(
        IHttpContextAccessor accessor//,
        //IOpenIddictAuthorizationManager authMgr,
        //IOpenIddictTokenManager tokMgr
    ) :
    IOpenIddictServerHandler<OpenIddictServerEvents.HandleEndSessionRequestContext>
{
    public async ValueTask HandleAsync(OpenIddictServerEvents.HandleEndSessionRequestContext ctx)
    {
        // Do not revoke tokens if the request is not a valid end session request.
        // User might be logged in on multiple devices, so we only remove the SSO cookie
        // 1) authenticate the cookie (if any)
        //var principal = (await accessor.HttpContext!
        //                        .AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme))
        //                        ?.Principal;

        //// 2) otherwise fall back to the id_token_hint analysed by OpenIddict
        //principal ??= ctx.IdentityTokenHintPrincipal;

        //// 3) revoke tokens/authorisations that belong to that user
        //if (principal is { }) { 
        //    await foreach (var auth in authMgr.ListAsync())
        //        await authMgr.TryRevokeAsync(auth);

        //    await foreach (var tok in tokMgr.ListAsync())
        //        await tokMgr.TryRevokeAsync(tok);
        //}

        // 4) remove the SSO cookie
        await accessor.HttpContext!.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

        // 5) let OpenIddict produce the normal response (redirect to SPA)
        ctx.SignOut();
    }
}
