using BlogPlatform.DTO.User.Request;
using FastEndpoints;
using FastEndpoints.Security;
using Microsoft.EntityFrameworkCore;

namespace BlogPlatform.Endpoints.User;

public class ConnectUserEndpoint(BlogPlatformDbContext db) : Endpoint<ConnectUserDto>
{
    public override void Configure()
    {
        Post("/api/login");
        AllowAnonymous();
    }

    public override async Task HandleAsync(ConnectUserDto req, CancellationToken ct)
    {
        
        var userLog = await db.Users.SingleOrDefaultAsync(x=>x.Username==req.Username, ct);
        if (userLog != null )
        {
            if (BCrypt.Net.BCrypt.Verify(req.Password+userLog.Salt, userLog.Password))
            {
                var jwtToken = JwtBearer.CreateToken(
                    o =>
                    {
                        o.SigningKey = "THCAUZUUZUZFUFDHFSJQIDJIQJDIQJSIQJZ";
                        o.ExpireAt = DateTime.UtcNow.AddDays(1);
                        o.User.Claims.Add(("UserName", userLog.Username));
                        o.User["UserId"] = "001"; //indexer based claim setting
                    });

                await Send.OkAsync(
                    new
                    {
                        req.Username,
                        Token = jwtToken
                    });
            }
            else
            {
                await Send.UnauthorizedAsync(ct);
            }
        }
        else
            await Send.UnauthorizedAsync(ct);

    }
}