using FastEndpoints;
using Shared.Problems;

namespace Modules.OMS.Orders.Register;

public sealed class Endpoint(RegisterOrderHandler handler)
    : Endpoint<RegisterOrderRequest, RegisterOrderResponse>
{
    public override void Configure()
    {
        Post("/api/oms/orders/register");
        Permissions("oms.order.create");
    }

    public override async Task HandleAsync(RegisterOrderRequest req, CancellationToken ct)
    {
        if (req.OrderId is not null)
        {
            await Send.ResponseAsync(KbxBusinessProblem.Create("ORDER_CREATE_ENDPOINT_ONLY", "신규 주문 등록 요청이 아닙니다.", "기존 주문 수정은 전용 수정 API를 사용하세요."), 409, cancellation: ct);
            return;
        }
        var result = await handler.HandleAsync(req with { OrderId = null, Version = null }, User, ct);

        if (result.Problem is KbxValidationProblem validation)
        {
            await Send.ResponseAsync(validation, 400, cancellation: ct);
            return;
        }
        if (result.Problem is KbxBusinessProblem business)
        {
            await Send.ResponseAsync(business, 409, cancellation: ct);
            return;
        }
        if (result.Problem is KbxConflictProblem conflict)
        {
            await Send.ResponseAsync(conflict, 409, cancellation: ct);
            return;
        }

        await Send.OkAsync(result.Response!, ct);
    }
}
