using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using StandManager.Domain.Entita;
using StandManager.Model;
using StandManager.Service.Interfaces;

public static class LoginUtils
{
    public static async Task<IResult> OnLogin(LoginModel model, IManagerService managerService, HttpContext ctx)
    {
        var user = await managerService.UtenteService.RicercaPer(x => x.Email == model.Email);
        var hasher = new PasswordHasher<Utente>();

        if (user == null || 
            hasher.VerifyHashedPassword(user, user.Password, model.Password) != PasswordVerificationResult.Success)
        {
            // credenziali non valide
            return Results.BadRequest("Credenziali non valide.");
        }

        List<Claim> claims =
        [
            new(ClaimTypes.Name, user.Email),
            new(ClaimTypes.GivenName, user.Nome),
            new("Id", user.Id.ToString())
        ];

        ClaimsIdentity identity = new(claims, "standmanager");
        ClaimsPrincipal claimsPrincipal = new(identity);

        await ctx.SignInAsync("standmanager", claimsPrincipal, new AuthenticationProperties
        {
            IsPersistent = true,
            ExpiresUtc = DateTime.UtcNow.AddHours(8)
        });

        return Results.Ok();
    }
}