using Backend.Contracts;
using Backend.Data;
using Backend.Domain;
using Backend.Security;
using Backend.Services;

namespace Backend.Endpoints;

public static partial class AuthEndpoints
{
    private static async Task<IResult> GetSession(
        HttpContext context,
        AwardsDbContext db,
        IUserSessionService userSessionService)
    {
        var session = await userSessionService.ResolveSessionAsync(context, context.RequestAborted);
        if (session is null)
        {
            return Results.Unauthorized();
        }

        return Results.Ok(await ToAuthSessionDtoAsync(db, session, false, context.RequestAborted));
    }

    private static async Task<IResult> Logout(HttpContext context, IUserSessionService userSessionService)
    {
        var session = await userSessionService.ResolveSessionAsync(context, context.RequestAborted);
        if (session is null)
        {
            return Results.Ok(new { loggedOut = true });
        }

        await userSessionService.LogoutAsync(session, context.RequestAborted);
        return Results.Ok(new { loggedOut = true });
    }

    private static async Task<AuthSessionDto> ToAuthSessionDtoAsync(
        AwardsDbContext db,
        UserSession session,
        bool mustChangePassword = false,
        CancellationToken cancellationToken = default)
    {
        var teamMember = await FindTeamMemberForSessionAsync(db, session, cancellationToken);
        var sessionRole = teamMember?.Role ?? session.Role;
        var permissionKeys = await AdminPermissionCatalog.GetPermissionKeysAsync(db, sessionRole, cancellationToken);
        return new(
            session.SessionToken,
            session.TwitchUserId,
            teamMember?.DisplayName ?? session.DisplayName,
            AdminRoles.Normalize(sessionRole),
            permissionKeys,
            teamMember?.MustChangePassword ?? mustChangePassword,
            teamMember?.Login,
            teamMember?.BoundTwitchUserId,
            teamMember?.BoundTwitchDisplayName);
    }
}
