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

namespace Knots.Endpoints.Group;

public class PatchGroupNameEndpoint(KnotsDbContext knotsDbContext) : Endpoint<UpdateGroupNameDto>
{
    public override void Configure()
    {
        Patch("/groups/{@Id}/name/", x => new {x.Id});
        AllowAnonymous();
    }

    public override async Task HandleAsync(UpdateGroupNameDto req, CancellationToken ct)
    {
        Models.Group? databaseGroup = await knotsDbContext.Groups.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);

        if (databaseGroup is null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }
        
        databaseGroup.Name = req.Name;
        await knotsDbContext.SaveChangesAsync(ct);
        await Send.NoContentAsync(ct);
    }
}