using ClosedXML.Excel;
using Jiaowu.Api.Controllers;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

namespace Jiaowu.Api.Tests;

public sealed class TeachingTaskRosterProfileTests
{
    [Fact]
    public async Task Assigned_teacher_receives_contact_and_special_fields_in_roster_and_export()
    {
        await using var connection = new SqliteConnection("Data Source=:memory:");
        await connection.OpenAsync();
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseSqlite(connection)
            .Options;
        await using var db = new AppDbContext(options);
        await db.Database.EnsureCreatedAsync();

        var teacherUser = User("T001", "任课教师");
        var studentUser = User("S001", "学生甲");
        var college = new College { Code = "CS", Name = "计算机学院" };
        var major = new Major
        {
            Code = "080901", Name = "计算机科学与技术",
            CollegeId = college.Id, DegreeType = "工学学士"
        };
        var administrativeClass = new AdministrativeClass
        {
            Code = "CS2026-01", Name = "计科一班", MajorId = major.Id, Grade = 2026
        };
        var teacher = new Teacher
        {
            TeacherNumber = "T001", Name = "任课教师", CollegeId = college.Id,
            UserId = teacherUser.Id
        };
        var student = new Student
        {
            StudentNumber = "S001", Name = "学生甲", UserId = studentUser.Id,
            AdministrativeClassId = administrativeClass.Id,
            EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1),
            Phone = "13800000000", Email = "s@example.edu.cn", WeChat = "student-wechat",
            EmergencyContactName = "家长", EmergencyContactRelationship = "母亲",
            EmergencyContactPhone = "13900000000", SpecialTags = "走读",
            SpecialNeeds = "需留意交通延误"
        };
        var term = new AcademicTerm
        {
            Code = "2026-1", Name = "2026-2027-1", AcademicYear = "2026-2027",
            Season = TermSeason.Autumn, StartDate = new DateOnly(2026, 9, 1),
            EndDate = new DateOnly(2027, 1, 20)
        };
        var course = new Course
        {
            Code = "CS101", Name = "程序设计", CollegeId = college.Id,
            Credits = 4, TotalHours = 64, LectureHours = 48, PracticeHours = 16,
            Nature = CourseNature.MajorRequired,
            AssessmentMethod = AssessmentMethod.Examination
        };
        db.AddRange(teacherUser, studentUser, college);
        await db.SaveChangesAsync();
        db.AddRange(major, teacher, term, course);
        await db.SaveChangesAsync();
        db.Add(administrativeClass);
        await db.SaveChangesAsync();
        db.Add(student);
        await db.SaveChangesAsync();
        var task = new TeachingTask
        {
            TaskNumber = "2026-CS101-01", Name = "程序设计教学班",
            AcademicTermId = term.Id, CourseId = course.Id, Capacity = 40,
            Status = TeachingTaskStatus.Published,
            Teachers = [new TeachingTaskTeacher { TeacherId = teacher.Id }],
            Classes = [new TeachingTaskClass { AdministrativeClassId = administrativeClass.Id }]
        };
        db.Add(task);
        await db.SaveChangesAsync();

        var controller = new CourseSelectionsController(
            db,
            new TeacherDataScope(teacherUser.Id));
        var rosterResult = Assert.IsType<OkObjectResult>(
            await controller.GetTeachingTaskRoster(task.Id, CancellationToken.None));
        var students = Assert.IsAssignableFrom<System.Collections.IEnumerable>(
            rosterResult.Value!.GetType().GetProperty("Students")!.GetValue(rosterResult.Value));
        var row = Assert.Single(students.Cast<object>());
        Assert.Equal("13800000000", Property(row, "Phone"));
        Assert.Equal("走读", Property(row, "SpecialTags"));
        Assert.Equal("需留意交通延误", Property(row, "SpecialNeeds"));

        var export = Assert.IsType<FileContentResult>(
            await controller.ExportTeachingTaskRoster(task.Id, CancellationToken.None));
        using var stream = new MemoryStream(export.FileContents);
        using var workbook = new XLWorkbook(stream);
        var sheet = workbook.Worksheet("教学班名单");
        Assert.Equal("联系电话", sheet.Cell(1, 5).GetString());
        Assert.Equal("特殊标记", sheet.Cell(1, 11).GetString());
        Assert.Equal("13800000000", sheet.Cell(2, 5).GetString());
        Assert.Equal("走读", sheet.Cell(2, 11).GetString());
    }

    private static string? Property(object value, string name) =>
        value.GetType().GetProperty(name)!.GetValue(value)?.ToString();

    private static ApplicationUser User(string userName, string displayName) => new()
    {
        Id = Guid.NewGuid(), UserName = userName,
        NormalizedUserName = userName.ToUpperInvariant(), DisplayName = displayName
    };

    private sealed class TeacherDataScope(Guid userId) : ICurrentUserDataScope
    {
        public CurrentUserScope Current { get; } = new(
            userId, "任课教师", null, DataScope.Self,
            new HashSet<string>([SystemRoles.Teacher]));
    }
}
