using Microsoft.EntityFrameworkCore;
using ROLAC.API.Data;

namespace ROLAC.API.Services.Ai;

/// <summary>
/// Loads AI settings from the singleton <c>ChurchProfile</c> row, substituting default model names
/// for any blank field so a freshly migrated install still names a valid model. The API keys are
/// passed through as-is (null when unset → the calling service treats AI as disabled).
/// </summary>
public sealed class ChurchAiConfigProvider : IChurchAiConfigProvider
{
    private const string DefaultClaudeModel = "claude-haiku-4-5-20251001";
    private const string DefaultGeminiModel = "gemini-2.5-flash-lite";

    private readonly AppDbContext _db;
    public ChurchAiConfigProvider(AppDbContext db) => _db = db;

    public async Task<ChurchAiConfig> GetAsync(CancellationToken ct = default)
    {
        var p = await _db.ChurchProfiles.AsNoTracking().OrderBy(x => x.Id).FirstOrDefaultAsync(ct);

        var provider = string.IsNullOrWhiteSpace(p?.AiProvider) ? "Claude" : p.AiProvider;
        var claudeModel = string.IsNullOrWhiteSpace(p?.ClaudeModel) ? DefaultClaudeModel : p!.ClaudeModel!;
        var geminiModel = string.IsNullOrWhiteSpace(p?.GeminiModel) ? DefaultGeminiModel : p!.GeminiModel!;

        return new ChurchAiConfig(provider, claudeModel, p?.ClaudeApiKey, geminiModel, p?.GeminiApiKey);
    }
}
