using System.Net;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using SVSim.Bootstrap.Importers;
using SVSim.Database;
using SVSim.UnitTests.Infrastructure;

namespace SVSim.UnitTests.Controllers;

/// <summary>
/// Drives the importer + controller against the full production pack seed (35 packs). Guards
/// against regressions in either layer caused by future seed refreshes.
/// </summary>
public class PackControllerFullCatalogTests
{
    [Test]
    public async Task Info_returns_full_35_pack_catalog_from_production_seed()
    {
        // The production seed (packs.json) is overlaid by a 3-pack test fixture in the default test
        // output dir (see SVSim.UnitTests.csproj). For this test we need the FULL 35-pack catalog,
        // so we point PackImporter at a temp seed dir holding only the upstream production seed
        // (copied from the Bootstrap project's source-tree Data/seeds/).
        var prodSeed = LocateProdSeed("packs.json");
        var tempSeedDir = Path.Combine(Path.GetTempPath(), "svsim-pack-prod-" + Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(tempSeedDir);
        try
        {
            File.Copy(prodSeed, Path.Combine(tempSeedDir, "packs.json"));

            using var factory = new SVSimTestFactory();
            // Run the default seed pipeline first so the per-domain importers populate surrounding tables,
            // then re-run PackImporter against the prod seed to overwrite the fixture-loaded packs.
            await factory.SeedGlobalsAsync();
            using (var scope = factory.Services.CreateScope())
            {
                var ctx = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
                await new PackImporter().ImportAsync(ctx, tempSeedDir);
            }

            long viewerId = await factory.SeedViewerAsync();

            using var client = factory.CreateAuthenticatedClient(viewerId);
            var response = await client.PostAsync(
                "/pack/info",
                new StringContent("""{"viewer_id":"0","steam_id":0,"steam_session_ticket":""}""",
                    Encoding.UTF8, "application/json"));

            var body = await response.Content.ReadAsStringAsync();
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK), body);

            using var doc = JsonDocument.Parse(body);
            var list = doc.RootElement.GetProperty("pack_config_list");
            Assert.That(list.GetArrayLength(), Is.EqualTo(35),
                "Full prod seed should yield 35 active packs as of 2026-05-23.");

            // Spot-check pack 99047 (LegendCardPack throwback, pack_category=1)
            bool sawSpecial = false;
            for (int i = 0; i < list.GetArrayLength(); i++)
            {
                var el = list[i];
                if (el.GetProperty("parent_gacha_id").GetInt32() == 99047)
                {
                    Assert.That(el.GetProperty("pack_category").GetInt32(), Is.EqualTo(1),
                        "99047 is a LegendCardPack (category 1) in the prod capture.");
                    sawSpecial = true;
                    break;
                }
            }
            Assert.That(sawSpecial, Is.True, "pack 99047 must be in the prod capture output.");
        }
        finally
        {
            try { Directory.Delete(tempSeedDir, recursive: true); } catch { /* best-effort cleanup */ }
        }
    }

    /// <summary>
    /// The test output dir's <c>Data/seeds/packs.json</c> is the fixture overlay (3 packs). The
    /// upstream production seed lives in the Bootstrap project's source tree. Walk up from the
    /// test binary dir to the repo root and locate it there.
    /// </summary>
    private static string LocateProdSeed(string fileName)
    {
        var dir = new DirectoryInfo(AppContext.BaseDirectory);
        while (dir is not null)
        {
            var candidate = Path.Combine(dir.FullName, "SVSim.Bootstrap", "Data", "seeds", fileName);
            if (File.Exists(candidate)) return candidate;
            dir = dir.Parent;
        }
        throw new FileNotFoundException(
            $"Could not locate SVSim.Bootstrap/Data/seeds/{fileName} above {AppContext.BaseDirectory}.");
    }
}
