using BlogPlatform.DTO.Comment.Request;
using BlogPlatform.DTO.Comment.Response;
using BlogPlatform.DTO.User.Request;
using BlogPlatform.DTO.User.Response;
using BlogPlatform.Models;
using FastEndpoints;
using PasswordGenerator;
using Singulink.Cryptography;

namespace BlogPlatform.Endpoints.User;

public class CreateUserEndpoint(BlogPlatformDbContext db) : Endpoint<CreateUserDto,GetUserDto>
{
    public override void Configure()
    {
        Post("/api/users/create");
    }

    public override async Task HandleAsync(CreateUserDto req, CancellationToken ct)
    {
        string? salt = new Password()
            .IncludeLowercase()
            .IncludeUppercase()
            .IncludeNumeric()
            .IncludeSpecial()
            .LengthRequired(24)
            .Next();
        
        
        Models.User user = new()
        {
            Username = req.Username,
            Email = req.Email,
            Password = BCrypt.Net.BCrypt.HashPassword(req.Password+salt),
            Salt = salt,
        };  
        
        db.Users.Add(user);
        await db.SaveChangesAsync(ct);

        GetUserDto dto = new()
        {
            Id = user.Id,
            Username = user.Username,
            Email = user.Email,
            Password = user.Password,
            Salt = user.Salt
        };
        
        await Send.OkAsync(dto, ct);

    }
}
