using FastEndpoints;
using Knots.DTO.User;
using Knots.Services;
using Microsoft.EntityFrameworkCore;

namespace Knots.Endpoints.User;

public class LoginEndpoint(KnotsDbContext db, JwtService jwtService) : Endpoint<LoginUserDto, LoginResponseDto>
{
    public override void Configure()
    {
        Post("/users/login");
        AllowAnonymous();
    }

    public override async Task HandleAsync(LoginUserDto req, CancellationToken ct)
    {
        Models.User? user = await db.Users
            .SingleOrDefaultAsync(x => x.Username == req.Username, cancellationToken: ct);

        if (user is null || !BCrypt.Net.BCrypt.Verify(req.Password, user.Password)) // hash à ajouter plus tard
        {
            await SendUnauthorizedAsync(ct);
            return;
        }

        string token = jwtService.GenerateToken(user);

        await SendOkAsync(new LoginResponseDto
        {
            Token = token,
            Id = user.Id,
            Username = user.Username!,
            Email = user.Email,
            Tel = user.Tel,
            ProfilePicture = user.ProfilePicture,
            Description = user.Description
        }, ct);
    }
}