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

namespace Knots.Endpoints.Group;

public class GetGroupEndpoint(KnotsDbContext db, AutoMapper.IMapper mapper) : Endpoint<GetGroupDetailsDto>
{
    public override void Configure()
    {
        Get("/groups");
        AllowAnonymous();
    }
    
    public override async Task HandleAsync(GetGroupDetailsDto req, CancellationToken ct)
    {
        Models.Group? databaseGroup = await db.Groups.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);     
        
        if (databaseGroup == null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }
        
        var keyDto = mapper.Map<GetKeyDetailsDto>(databaseGroup);
        await Send.OkAsync(keyDto, ct);
    }
}