using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using SVSim.Bootstrap.Models.Seed;
using SVSim.Database;
using SVSim.Database.Models;

namespace SVSim.Bootstrap.Importers;

/// <summary>
/// Idempotent upsert of daily-login-bonus campaign rows from <c>seeds/daily-login-bonus.json</c>.
/// <c>bonus_data</c> array preserved verbatim — prod observed empty arrays outside active events.
/// </summary>
public class DailyLoginBonusImporter
{
    public async Task<int> ImportAsync(SVSimDbContext context, string seedDir)
    {
        var seed = SeedLoader.LoadList<DailyLoginBonusSeed>(Path.Combine(seedDir, "daily-login-bonus.json"));
        if (seed.Count == 0) return 0;

        var existing = await context.DailyLoginBonuses.ToDictionaryAsync(e => e.Id);
        int created = 0, updated = 0;
        foreach (var s in seed)
        {
            if (s.Id == 0) continue;
            var entry = existing.TryGetValue(s.Id, out var ex) ? ex : new DailyLoginBonusEntry { Id = s.Id };
            entry.BonusData = s.BonusData.ValueKind == JsonValueKind.Undefined
                ? "[]"
                : JsonSerializer.Serialize(s.BonusData);
            if (ex is null) { context.DailyLoginBonuses.Add(entry); existing[s.Id] = entry; created++; }
            else updated++;
        }

        await context.SaveChangesAsync();
        Console.WriteLine($"[DailyLoginBonusImporter] +{created}/~{updated}");
        return created + updated;
    }
}
