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

namespace Knots.Endpoints.Message;

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

    public override async Task HandleAsync(GetMessageDetailsDto req, CancellationToken ct)
    {
        Models.Message? databaseMessage = await db.Messages.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);     
        
        if (databaseMessage == null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }
        
        var messageDto = mapper.Map<GetMessageDetailsDto>(databaseMessage);
        await Send.OkAsync(messageDto, ct);
    }
}