using System.Text.Json.Nodes;
using ClosedXML.Excel;
using Eis.Infrastructure.Spreadsheets;

namespace Eis.Infrastructure.Tests.Spreadsheets;

public sealed class SystemWorkbookTests
{
    [Fact]
    public void AdmissionReporting_RoundTripsEditableFieldsAndKeepsProfessionalLayout()
    {
        var content = SystemWorkbook.Build(
            "admission_reporting",
            [
                new JsonObject
                {
                    ["noticeNumber"] = "AD01-EX-2026-ZK-000001",
                    ["candidateNumber"] = "2026-HZ01-F-0001",
                    ["name"] = "张同学",
                    ["examCode"] = "EX-2026-ZK",
                    ["schoolCode"] = "AD01",
                    ["categoryName"] = "普通生",
                    ["reportingStatusCode"] = "Y",
                    ["reportingNote"] = "材料齐全"
                }
            ],
            subtitle: "第 1 轮");

        using var workbook = new XLWorkbook(new MemoryStream(content));
        var sheet = workbook.Worksheet("考生报到");

        Assert.True(content.Length > 1000);
        Assert.Equal(XLColor.FromHtml("#173F60"), sheet.Cell(1, 1).Style.Fill.BackgroundColor);
        Assert.Equal(XLColor.FromHtml("#FFF3CD"), sheet.Cell(3, 7).Style.Fill.BackgroundColor);
        Assert.Equal(XLColor.FromHtml("#FFF3CD"), sheet.Cell(3, 8).Style.Fill.BackgroundColor);

        var parsed = SystemWorkbook.Parse("admission_reporting", content);
        Assert.Single(parsed);
        Assert.Equal("Y", parsed[0]["reportingStatusCode"]!.GetValue<string>());
        Assert.Equal("材料齐全", parsed[0]["reportingNote"]!.GetValue<string>());
        Assert.Equal(3, parsed[0]["__row"]!.GetValue<int>());
    }

    [Fact]
    public void Template_ContainsExampleRowAndValidation()
    {
        var content = SystemWorkbook.Build("classes", [], template: true);

        using var workbook = new XLWorkbook(new MemoryStream(content));
        var sheet = workbook.Worksheet("班级");

        Assert.Equal("HZ01", sheet.Cell(3, 1).GetString());
        Assert.Equal("启用", sheet.Cell(3, 4).GetString());
        Assert.NotEmpty(sheet.DataValidations);
    }

    [Fact]
    public void InvalidWorkbook_IsRejectedWithBusinessError()
    {
        var error = Assert.Throws<WorkbookException>(() =>
            SystemWorkbook.Parse("results", "not-an-xlsx"u8.ToArray()));

        Assert.Equal(400, error.StatusCode);
        Assert.Contains("系统下载的 .xlsx 模板", error.Message, StringComparison.Ordinal);
    }
}
