using FastEndpoints;

namespace SpaceGame.Api.PlayerFaction.Api;

public sealed class UpdatePlayerOrganizationMembershipHandler(WorldService worldService) : Endpoint<PlayerOrganizationMembershipCommandRequest, PlayerFactionSnapshot>
{
    public override void Configure()
    {
        Put("/api/player-faction/organizations/{organizationId}/membership");
    }

    public override async Task HandleAsync(PlayerOrganizationMembershipCommandRequest request, CancellationToken cancellationToken)
    {
        try
        {
            var organizationId = Route<string>("organizationId");
            if (string.IsNullOrWhiteSpace(organizationId))
            {
                AddError("organizationId route parameter is required.");
                await SendErrorsAsync(cancellation: cancellationToken);
                return;
            }

            var snapshot = worldService.UpdatePlayerOrganizationMembership(organizationId, request);
            if (snapshot is null)
            {
                await SendNotFoundAsync(cancellationToken);
                return;
            }

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