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

namespace Knots.Endpoints.User;


public class PatchUsernameEndpoint(KnotsDbContext db, AutoMapper.IMapper mapper) : Endpoint<UpdateUsernameDto>
{
    public override void Configure()
    {
        Patch("/users/{@Id}/username/");
        AllowAnonymous();
    }

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

        if (databaseUser is null)
        {
            await SendNotFoundAsync(ct);
            return;
        }
        
        bool usernameExists = await db.Users
            .AnyAsync(x => x.Username == req.Username && x.Id != req.Id, cancellationToken: ct);

        if (usernameExists)
        {
            AddError(x => x.Username, "Ce nom d'utilisateur est déjà pris.");
            await SendErrorsAsync(cancellation: ct);
            return;
        }
        
        mapper.Map(req, databaseUser);

        await db.SaveChangesAsync(ct);
        await SendNoContentAsync(ct);
    }
}