using ClosedXML.Excel;
using Jiaowu.Api.Infrastructure.Exams;

namespace Jiaowu.Api.Tests;

public sealed class ExamSignInWorkbookExporterTests
{
    [Fact]
    public void Create_builds_summary_and_printable_session_sheets()
    {
        var sessionId = Guid.NewGuid();
        var session = new ExamSignInSessionData(
            sessionId,
            new DateOnly(2027, 1, 8),
            new DateTime(2027, 1, 8, 8, 0, 0, DateTimeKind.Utc),
            new DateTime(2027, 1, 8, 9, 50, 0, DateTimeKind.Utc),
            "CS101",
            "程序设计基础",
            "2026-1-CS101-01",
            "第一教学楼",
            "101",
            ["张老师", "李老师"],
            [
                new ExamSignInStudentData(
                    Guid.NewGuid(),
                    "202601001",
                    "周同学",
                    "计科 2026-1 班")
            ]);
        var data = new ExamSignInWorkbookData(
            "2026—2027 学年第一学期期末考试",
            "2026—2027 学年第一学期",
            [
                session,
                session with { SessionId = Guid.NewGuid() }
            ]);

        var bytes = ExamSignInWorkbookExporter.Create(data);

        using var stream = new MemoryStream(bytes);
        using var workbook = new XLWorkbook(stream);
        Assert.Equal(3, workbook.Worksheets.Count);
        Assert.Equal("考场汇总", workbook.Worksheet(1).Name);
        Assert.Equal(1, workbook.Worksheet("考场汇总").Cell("F5").GetDouble());
        Assert.Equal(1, workbook.Worksheet("考场汇总").Cell("F6").GetDouble());
        Assert.Equal(
            workbook.Worksheets.Count,
            workbook.Worksheets.Select(x => x.Name)
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .Count());

        var signInSheet = workbook.Worksheet(2);
        Assert.Equal("考试考场签名单", signInSheet.Cell("A1").GetString());
        Assert.Contains("第一教学楼", signInSheet.Cell("E4").GetString());
        Assert.Equal("202601001", signInSheet.Cell("C8").GetString());
        Assert.Equal("周同学", signInSheet.Cell("D8").GetString());
        Assert.Equal(XLPageOrientation.Portrait, signInSheet.PageSetup.PageOrientation);
        Assert.Equal(XLPaperSize.A4Paper, signInSheet.PageSetup.PaperSize);
    }
}
