using System.Net;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SVSim.Database;
using SVSim.Database.Enums;
using SVSim.Database.Models;
using SVSim.UnitTests.Infrastructure;

namespace SVSim.UnitTests.Controllers;

public class PackControllerInfoTests
{
    private const string EmptyEnvelope = """{"viewer_id":"0","steam_id":0,"steam_session_ticket":""}""";

    private static StringContent JsonBody(string json) => new(json, Encoding.UTF8, "application/json");

    private static async Task SeedActivePack(SVSimTestFactory f, int parentId, int baseId, PackCategory cat)
    {
        using var scope = f.Services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
        db.Packs.Add(new PackConfigEntry
        {
            Id = parentId, BasePackId = baseId, PackCategory = cat,
            CommenceDate = DateTime.UtcNow.AddDays(-1), CompleteDate = DateTime.UtcNow.AddDays(30),
            GachaType = 1, GachaDetail = "test",
            ChildGachas = { new PackChildGachaEntry { GachaId = parentId * 10 + 7, TypeDetail = 7, Cost = 100, CardCount = 8 } },
        });
        await db.SaveChangesAsync();
    }

    [Test]
    public async Task Info_returns_active_packs_only()
    {
        using var factory = new SVSimTestFactory();
        long viewerId = await factory.SeedViewerAsync();
        await SeedActivePack(factory, 10001, 10001, PackCategory.None);

        using var client = factory.CreateAuthenticatedClient(viewerId);
        var response = await client.PostAsync("/pack/info", JsonBody(EmptyEnvelope));

        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(1));
        Assert.That(list[0].GetProperty("parent_gacha_id").GetInt32(), Is.EqualTo(10001));
    }

    [Test]
    public async Task Info_overlays_viewer_open_count()
    {
        using var factory = new SVSimTestFactory();
        long viewerId = await factory.SeedViewerAsync();
        await SeedActivePack(factory, 10001, 10001, PackCategory.None);

        using (var scope = factory.Services.CreateScope())
        {
            var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
            var v = await db.Viewers.Include(x => x.PackOpenCounts).FirstAsync(x => x.Id == viewerId);
            v.PackOpenCounts.Add(new ViewerPackOpenCount { PackId = 10001, OpenCount = 7 });
            await db.SaveChangesAsync();
        }

        using var client = factory.CreateAuthenticatedClient(viewerId);
        var response = await client.PostAsync("/pack/info", JsonBody(EmptyEnvelope));
        var body = await response.Content.ReadAsStringAsync();

        using var doc = JsonDocument.Parse(body);
        var p = doc.RootElement.GetProperty("pack_config_list")[0];
        Assert.That(p.GetProperty("open_count").GetInt32(), Is.EqualTo(7));
    }

    [Test]
    public async Task Info_emits_child_gacha_info_with_correct_wire_keys()
    {
        using var factory = new SVSimTestFactory();
        long viewerId = await factory.SeedViewerAsync();
        await SeedActivePack(factory, 10001, 10001, PackCategory.None);

        using var client = factory.CreateAuthenticatedClient(viewerId);
        var response = await client.PostAsync("/pack/info", JsonBody(EmptyEnvelope));
        var body = await response.Content.ReadAsStringAsync();

        using var doc = JsonDocument.Parse(body);
        var children = doc.RootElement.GetProperty("pack_config_list")[0].GetProperty("child_gacha_info");
        Assert.That(children.GetArrayLength(), Is.EqualTo(1));
        Assert.That(children[0].GetProperty("type_detail").GetInt32(), Is.EqualTo(7));
        Assert.That(children[0].GetProperty("cost").GetInt32(), Is.EqualTo(100));
    }

    [Test]
    public async Task Info_emits_gacha_point_key_as_null_when_pack_has_no_gacha_point_config()
    {
        // PackInfoTask.cs:126 does `if (jsonData2["gacha_point"] != null)`. LitJson's JsonData
        // indexer throws KeyNotFoundException on missing keys — the null check protects against
        // null *value*, not missing *key*. With Program.cs's global WhenWritingNull, a null
        // PackGachaPointDto would be omitted entirely and crash the client. Override per
        // [[project_wire_null_policy]].
        using var factory = new SVSimTestFactory();
        long viewerId = await factory.SeedViewerAsync();
        // Seed a pack WITHOUT GachaPointConfig — matches packs 80047, 92001, 99047 in prod
        // (legendary specials whose `gacha_point` is null).
        using (var scope = factory.Services.CreateScope())
        {
            var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
            db.Packs.Add(new PackConfigEntry
            {
                Id = 92001, BasePackId = 90001, PackCategory = PackCategory.LegendCardPack,
                CommenceDate = DateTime.UtcNow.AddDays(-1), CompleteDate = DateTime.UtcNow.AddDays(30),
                GachaType = 1, GachaDetail = "legendary special", SleeveId = 5090001,
                GachaPointConfig = null,
                ChildGachas = { new PackChildGachaEntry { GachaId = 920002, TypeDetail = 5, Cost = 1, CardCount = 8, ItemId = 92001 } },
            });
            await db.SaveChangesAsync();
        }

        using var client = factory.CreateAuthenticatedClient(viewerId);
        var response = await client.PostAsync("/pack/info", JsonBody(EmptyEnvelope));
        var body = await response.Content.ReadAsStringAsync();

        using var doc = JsonDocument.Parse(body);
        var pack = doc.RootElement.GetProperty("pack_config_list")[0];

        // The key MUST be present, even though its value is null.
        Assert.That(pack.TryGetProperty("gacha_point", out var gachaPoint), Is.True,
            "gacha_point key must always be present in /pack/info — client at PackInfoTask.cs:126 does a direct key access guarded only by a null check, not Keys.Contains.");
        Assert.That(gachaPoint.ValueKind, Is.EqualTo(JsonValueKind.Null),
            "gacha_point should serialize as explicit null when no GachaPointConfig is set.");
    }
}
