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

namespace Knots.Endpoints.Discussion;

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