using Jiaowu.Api.Infrastructure.Excel;
using Microsoft.AspNetCore.Http;

namespace Jiaowu.Api.Tests;

public sealed class ExcelWorkbookHelperTests
{
    [Fact]
    public async Task Workbook_round_trip_preserves_headers_and_values()
    {
        var bytes = ExcelWorkbookHelper.Create(
            "教师档案",
            ["工号", "姓名", "入职日期"],
            [
                new object?[]
                {
                    "T001",
                    "陈老师",
                    new DateOnly(2026, 9, 1)
                }
            ],
            ["测试说明"]);
        await using var stream = new MemoryStream(bytes);
        var file = new FormFile(stream, 0, bytes.Length, "file", "teachers.xlsx");

        var rows = await ExcelWorkbookHelper.ReadAsync(
            file,
            ["工号", "姓名", "入职日期"],
            CancellationToken.None);

        var row = Assert.Single(rows);
        Assert.Equal(2, row.RowNumber);
        Assert.Equal("T001", row["工号"]);
        Assert.Equal("陈老师", row["姓名"]);
        Assert.Equal("2026-09-01", row["入职日期"]);
    }

    [Fact]
    public async Task Workbook_reader_rejects_missing_required_headers()
    {
        var bytes = ExcelWorkbookHelper.Create(
            "账号导入",
            ["登录账号"],
            [new object?[] { "admin" }]);
        await using var stream = new MemoryStream(bytes);
        var file = new FormFile(stream, 0, bytes.Length, "file", "users.xlsx");

        var exception = await Assert.ThrowsAsync<InvalidDataException>(() =>
            ExcelWorkbookHelper.ReadAsync(
                file,
                ["登录账号", "角色"],
                CancellationToken.None));

        Assert.Contains("角色", exception.Message);
    }
}
