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

namespace Knots.Endpoints.User;

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

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

        if (databaseUser is null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }
        
        mapper.Map(req, databaseUser);

        await db.SaveChangesAsync(ct);
        await Send.NoContentAsync(ct);
    }
}