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, userSessionService, 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,
        IUserSessionService userSessionService,
        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);
        var sessionIdleTimeoutHours = await userSessionService.GetIdleTimeoutHoursAsync(cancellationToken);
        return new(
            session.SessionToken,
            session.TwitchUserId,
            teamMember?.DisplayName ?? session.DisplayName,
            AdminRoles.Normalize(sessionRole),
            permissionKeys,
            sessionIdleTimeoutHours,
            teamMember?.MustChangePassword ?? mustChangePassword,
            teamMember?.Login,
            teamMember?.BoundTwitchUserId,
            teamMember?.BoundTwitchDisplayName);
    }
}
