using JobsMedical.Web.Data;
using JobsMedical.Web.Models;
using Microsoft.EntityFrameworkCore;

namespace JobsMedical.Web.Services.Scraping;

/// <summary>Loads/creates the single platform-settings row (Id=1).</summary>
public class SettingsService
{
    private readonly AppDbContext _db;
    public SettingsService(AppDbContext db) => _db = db;

    public async Task<AppSetting> GetAsync()
    {
        var s = await _db.AppSettings.FirstOrDefaultAsync(x => x.Id == 1);
        if (s is null)
        {
            s = new AppSetting { Id = 1 };
            _db.AppSettings.Add(s);
            await _db.SaveChangesAsync();
        }
        return s;
    }

    public async Task SaveAsync(AppSetting incoming)
    {
        var s = await GetAsync();
        s.Mode = incoming.Mode;
        s.AutoPublishMinConfidence = Math.Clamp(incoming.AutoPublishMinConfidence, 0, 100);
        s.AiEnabled = incoming.AiEnabled;
        s.AiEndpoint = incoming.AiEndpoint?.Trim();
        s.AiApiKey = incoming.AiApiKey?.Trim();
        s.AiModel = incoming.AiModel?.Trim();
        s.AiSystemPrompt = string.IsNullOrWhiteSpace(incoming.AiSystemPrompt)
            ? AppSetting.DefaultPrompt : incoming.AiSystemPrompt;
        s.AiAutoApprove = incoming.AiAutoApprove;
        // Channel scraping sources
        s.AutoIngestEnabled = incoming.AutoIngestEnabled;
        s.IngestIntervalMinutes = Math.Max(1, incoming.IngestIntervalMinutes);
        s.TelegramEnabled = incoming.TelegramEnabled;
        s.TelegramChannels = incoming.TelegramChannels?.Trim();
        s.BaleEnabled = incoming.BaleEnabled;
        s.BaleBotToken = incoming.BaleBotToken?.Trim();
        s.DivarEnabled = incoming.DivarEnabled;
        s.DivarCity = string.IsNullOrWhiteSpace(incoming.DivarCity) ? "tehran" : incoming.DivarCity.Trim();
        s.DivarQueries = incoming.DivarQueries?.Trim();
        s.MedjobsEnabled = incoming.MedjobsEnabled;
        s.MedjobsMaxAds = Math.Clamp(incoming.MedjobsMaxAds, 1, 500);
        s.UpdatedAt = DateTime.UtcNow;
        await _db.SaveChangesAsync();
    }
}
