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

namespace Knots.Endpoints.Key;

public class GetKeyEndpoint(KnotsDbContext db, AutoMapper.IMapper mapper) : Endpoint <GetKeyDetailsDto>
{
    public override void Configure()
    { 
        Get("/keys/{@Id}");
        AllowAnonymous();
    }

    public override async Task HandleAsync(GetKeyDetailsDto req, CancellationToken ct)
    {
        Models.Key? databaseKey = await db.Keys.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);     
        
        if (databaseKey == null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }
        
        var keyDto = mapper.Map<GetKeyDetailsDto>(databaseKey);
        await Send.OkAsync(keyDto, ct);
    }
}