using FastEndpoints;

namespace SpaceGame.Api.Ships.Api;

public sealed class EnqueueShipOrderHandler(WorldService worldService) : Endpoint<ShipOrderCommandRequest, ShipSnapshot>
{
    public override void Configure()
    {
        Post("/api/ships/{shipId}/orders");
    }

    public override async Task HandleAsync(ShipOrderCommandRequest request, CancellationToken cancellationToken)
    {
        var shipId = Route<string>("shipId");
        if (string.IsNullOrWhiteSpace(shipId))
        {
            await SendNotFoundAsync(cancellationToken);
            return;
        }

        try
        {
            var snapshot = worldService.EnqueueShipOrder(shipId, request);
            if (snapshot is null)
            {
                await SendNotFoundAsync(cancellationToken);
                return;
            }

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