using GerbilManagerWebAPI.Ai;
using Microsoft.Extensions.Options;

namespace GerbilManagerWebAPI.SaleAd
{
    /// <summary>
    /// FEAT-12a: sale-ad generation. The provider-agnostic wire handling lives in
    /// <see cref="OpenAiChatClient"/> (extracted in INBOX-2 so the reply-draft and
    /// future AI features reuse the SAME implementation); this service contributes
    /// the sale-ad prompts and the SaleAd-shaped result. Public surface unchanged.
    /// </summary>
    public sealed class SaleAdService(HttpClient http, IOptions<AiOptions> options)
    {
        private readonly OpenAiChatClient _client = new(http, options);

        public async Task<SaleAdResult> GenerateAsync(SaleAdRequest request, CancellationToken ct = default)
        {
            var result = await _client.CompleteAsync(
                SaleAdPromptBuilder.BuildSystemPrompt(),
                SaleAdPromptBuilder.BuildUserPrompt(request),
                ct);
            var status = result.Status switch
            {
                AiCallStatus.Ok => SaleAdStatus.Ok,
                AiCallStatus.NotConfigured => SaleAdStatus.NotConfigured,
                _ => SaleAdStatus.UpstreamError,
            };
            return new SaleAdResult(status, result.Text, result.Error);
        }

        /// <summary>Forwarder kept for the existing config-matrix tests.</summary>
        internal static Uri BuildCompletionsUri(string baseUrl) =>
            OpenAiChatClient.BuildCompletionsUri(baseUrl);
    }
}
