using GerbilManagerWebAPI.SaleAd;

namespace GerbilManagerWebAPI.Endpoints
{
    /// <summary>
    /// FEAT-12a: POST /gerbils/sale-ad — AI-gestütztes Abgabe-Inserat (frozen
    /// contract, see gerbil-manager-web/src/api/saleAd.ts).
    ///
    /// 503 {code:"AiKeyMissing"} while the AI section is unconfigured — the
    /// frontend maps exactly this code to its German disabled-state hint.
    /// </summary>
    public static class SaleAdEndpoints
    {
        public static IEndpointRouteBuilder MapSaleAdEndpoints(this IEndpointRouteBuilder app)
        {
            app.MapPost("/gerbils/sale-ad",
                async (SaleAdRequest request, SaleAdService service, CancellationToken ct) =>
                {
                    var result = await service.GenerateAsync(request, ct);
                    return result.Status switch
                    {
                        SaleAdStatus.Ok => Results.Ok(new SaleAdResponse(result.Text!)),
                        SaleAdStatus.NotConfigured => Results.Json(
                            new SaleAdError("AiKeyMissing", result.Error ?? ""), statusCode: 503),
                        _ => Results.Json(
                            new SaleAdError("AiUpstreamError", result.Error ?? ""), statusCode: 502),
                    };
                })
                .WithTags("SaleAd");

            return app;
        }
    }
}
