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

namespace Knots.Endpoints.User;

public class GetUserEndpoint(KnotsDbContext db, AutoMapper.IMapper mapper) : Endpoint <GetUserDetailsDto>
{
    public override void Configure()
    { 
        Get ("/users/{@Id}", x => new { x.Username });
        AllowAnonymous();
    }

    public override async Task HandleAsync(GetUserDetailsDto req, CancellationToken ct)
    {
        Models.User? databaseUser = await db.Users.SingleOrDefaultAsync(x => x.Username == req.Username, cancellationToken: ct);     
        
        if (databaseUser == null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }
        
        var userDto = mapper.Map<GetUserDetailsDto>(databaseUser);
        await Send.OkAsync(userDto, ct);
    }
}