using FastEndpoints;

namespace SpaceGame.Api.PlayerFaction.Api;

public sealed class CreatePlayerOrganizationHandler(WorldService worldService) : Endpoint<PlayerOrganizationCommandRequest, PlayerFactionSnapshot>
{
    public override void Configure()
    {
        Post("/api/player-faction/organizations");
    }

    public override async Task HandleAsync(PlayerOrganizationCommandRequest request, CancellationToken cancellationToken)
    {
        try
        {
            var snapshot = worldService.CreatePlayerOrganization(request);
            if (snapshot is null)
            {
                await SendNotFoundAsync(cancellationToken);
                return;
            }

            await SendOkAsync(snapshot, cancellationToken);
        }
        catch (InvalidOperationException ex)
        {
            AddError(ex.Message);
            await SendErrorsAsync(cancellation: cancellationToken);
        }
    }
}
