using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Infrastructure.Exams;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Timetables;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

namespace Jiaowu.Api.Tests;

public sealed class ExamArrangementServiceTests
{
    [Fact]
    public async Task Normal_arrangement_creates_room_seats_for_selected_session()
    {
        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 seed = await SeedBaseDataAsync(db, "NORMAL");

        var plan = new ExamPlan
        {
            AcademicTermId = seed.Term.Id,
            Name = "期末考试"
        };
        var selected = NewExamSession(plan.Id, seed.FirstTask.Id);
        var untouched = NewExamSession(plan.Id, seed.SecondTask.Id);
        plan.Sessions.Add(selected);
        plan.Sessions.Add(untouched);
        db.ExamPlans.Add(plan);
        await db.SaveChangesAsync();
        db.ChangeTracker.Clear();

        var result = await new ExamArrangementService(db).ArrangeAsync(
            plan.Id,
            [selected.Id],
            assignClassrooms: true,
            assignInvigilators: true,
            CancellationToken.None);

        var room = await db.ExamRooms
            .Include(x => x.SessionLinks)
            .Include(x => x.Seats)
            .Include(x => x.Invigilators)
            .SingleAsync();
        Assert.True(result.Success);
        Assert.Equal(seed.LargeClassroom.Id, room.ClassroomId);
        Assert.Equal(selected.Id, Assert.Single(room.SessionLinks).ExamSessionId);
        Assert.Equal(3, room.Seats.Count);
        Assert.Single(room.Invigilators);
        Assert.False(await db.ExamRoomSessions.AnyAsync(
            x => x.ExamSessionId == untouched.Id));
        Assert.Contains("1个教学班场次处理完成", result.Message);
        Assert.Contains("1名监考教师", result.Message);
        Assert.Contains("程序设计", result.Message);

        plan = await db.ExamPlans.SingleAsync(x => x.Id == plan.Id);
        plan.Status = ExamPlanStatus.Published;
        await db.SaveChangesAsync();
        db.ChangeTracker.Clear();

        var timetableService = new TimetableDataService(db);
        var classroomTimetable = await timetableService.BuildAsync(
            TimetableResourceType.Classroom,
            seed.LargeClassroom.Id,
            seed.Term.Id,
            null,
            false,
            null,
            null,
            CancellationToken.None);
        var unrelatedClassroomTimetable = await timetableService.BuildAsync(
            TimetableResourceType.Classroom,
            seed.SmallClassroom.Id,
            seed.Term.Id,
            null,
            false,
            null,
            null,
            CancellationToken.None);
        var invigilatorTimetable = await timetableService.BuildAsync(
            TimetableResourceType.Teacher,
            room.Invigilators.Single().TeacherId,
            seed.Term.Id,
            null,
            false,
            null,
            null,
            CancellationToken.None);

        Assert.Equal(
            "程序设计",
            Assert.Single(classroomTimetable!.ExamEntries).CourseName);
        Assert.Empty(unrelatedClassroomTimetable!.ExamEntries);
        Assert.Contains(
            "监考：监考教师",
            Assert.Single(invigilatorTimetable!.ExamEntries).TeacherNames);
    }

    [Fact]
    public async Task Same_course_sessions_are_interleaved_and_split_across_rooms()
    {
        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 seed = await SeedBaseDataAsync(db, "MIXED");
        seed.LargeClassroom.Capacity = 8;
        seed.SmallClassroom.Capacity = 4;

        var plan = new ExamPlan
        {
            AcademicTermId = seed.Term.Id,
            Name = "期末考试"
        };
        var first = NewExamSession(plan.Id, seed.FirstTask.Id);
        var second = NewExamSession(plan.Id, seed.SameCourseTask.Id);
        plan.Sessions.Add(first);
        plan.Sessions.Add(second);
        db.ExamPlans.Add(plan);
        await db.SaveChangesAsync();
        db.ChangeTracker.Clear();

        var result = await new ExamArrangementService(db).ArrangeAsync(
            plan.Id,
            [first.Id],
            assignClassrooms: true,
            assignInvigilators: false,
            CancellationToken.None);

        var rooms = await db.ExamRooms
            .Include(x => x.SessionLinks)
            .Include(x => x.Seats)
            .OrderByDescending(x => x.Seats.Count)
            .ToListAsync();
        Assert.True(result.Success);
        Assert.Equal(2, rooms.Count);
        Assert.Equal([4, 2], rooms.Select(x => x.Seats.Count).ToArray());
        Assert.All(rooms, room =>
        {
            Assert.Equal(2, room.SessionLinks.Count);
            Assert.Equal(2, room.Seats.Select(x => x.ExamSessionId).Distinct().Count());
            Assert.True(room.Seats.Count <= 4);
        });
        Assert.Equal(6, await db.ExamSeats.CountAsync());
        Assert.Contains("2个教学班混排至2个考场", result.Message);
        Assert.Contains("自动包含同组1个场次", result.Message);

        plan = await db.ExamPlans.SingleAsync(x => x.Id == plan.Id);
        plan.Status = ExamPlanStatus.Published;
        await db.SaveChangesAsync();
        db.ChangeTracker.Clear();

        var student = await db.Students.AsNoTracking()
            .OrderBy(x => x.StudentNumber)
            .FirstAsync();
        var timetableService = new TimetableDataService(db);
        var classTimetable = await timetableService.BuildAsync(
            TimetableResourceType.Class,
            student.AdministrativeClassId,
            seed.Term.Id,
            null,
            false,
            null,
            null,
            CancellationToken.None);
        var studentTimetable = await timetableService.BuildAsync(
            TimetableResourceType.Class,
            student.AdministrativeClassId,
            seed.Term.Id,
            null,
            false,
            student.Id,
            new TimetableStudentDto(student.StudentNumber, student.Name),
            CancellationToken.None);

        var classExam = Assert.Single(classTimetable!.ExamEntries);
        Assert.Equal(first.Id, classExam.Id);
        Assert.Equal(2, classExam.ExamRoomCount);
        Assert.Equal("分散至 2 个考场", classExam.ClassroomName);
        Assert.DoesNotContain("监考：", classExam.TeacherNames);

        var studentExam = Assert.Single(studentTimetable!.ExamEntries);
        Assert.Equal(1, studentExam.ExamRoomCount);
        Assert.Contains(
            studentExam.ClassroomName,
            new[] { seed.LargeClassroom.Name, seed.SmallClassroom.Name });
    }

    [Fact]
    public async Task Makeup_arrangement_only_updates_selected_session()
    {
        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 seed = await SeedBaseDataAsync(db, "MAKEUP");

        var plan = new MakeupExamPlan
        {
            AcademicTermId = seed.Term.Id,
            Name = "补考计划"
        };
        var selected = NewMakeupExamSession(plan.Id, seed.FirstTask.Id);
        var untouched = NewMakeupExamSession(plan.Id, seed.SecondTask.Id);
        plan.Sessions.Add(selected);
        plan.Sessions.Add(untouched);
        db.MakeupExamPlans.Add(plan);
        await db.SaveChangesAsync();
        db.ChangeTracker.Clear();

        var result = await new MakeupExamArrangementService(db).ArrangeAsync(
            plan.Id,
            [selected.Id],
            assignClassrooms: true,
            assignInvigilators: true,
            CancellationToken.None);

        var persistedSelected = await db.MakeupExamSessions
            .Include(x => x.Invigilators)
            .SingleAsync(x => x.Id == selected.Id);
        var persistedUntouched = await db.MakeupExamSessions
            .Include(x => x.Invigilators)
            .SingleAsync(x => x.Id == untouched.Id);
        Assert.True(result.Success);
        Assert.NotNull(persistedSelected.ClassroomId);
        Assert.Null(persistedUntouched.ClassroomId);
        Assert.Single(persistedSelected.Invigilators);
        Assert.Empty(persistedUntouched.Invigilators);
        Assert.Contains("1个场次处理完成", result.Message);
        Assert.Contains("1名监考教师", result.Message);
        Assert.Contains("程序设计", result.Message);
    }

    private static ExamSession NewExamSession(Guid planId, Guid taskId) => new()
    {
        ExamPlanId = planId,
        TeachingTaskId = taskId,
        ExamDate = new DateOnly(2026, 12, 28),
        StartPeriod = 1,
        PeriodCount = 2,
        StartsAt = new DateTime(2026, 12, 28, 8, 0, 0, DateTimeKind.Utc),
        EndsAt = new DateTime(2026, 12, 28, 9, 50, 0, DateTimeKind.Utc),
        RequiredInvigilatorCount = 1
    };

    private static MakeupExamSession NewMakeupExamSession(Guid planId, Guid taskId) => new()
    {
        MakeupExamPlanId = planId,
        TeachingTaskId = taskId,
        ExamDate = new DateOnly(2026, 12, 28),
        StartPeriod = 1,
        PeriodCount = 2,
        StartsAt = new DateTime(2026, 12, 28, 8, 0, 0, DateTimeKind.Utc),
        EndsAt = new DateTime(2026, 12, 28, 9, 50, 0, DateTimeKind.Utc),
        RequiredInvigilatorCount = 1
    };

    private static async Task<SeedData> SeedBaseDataAsync(AppDbContext db, string suffix)
    {
        var term = new AcademicTerm
        {
            Code = $"2026-{suffix}",
            Name = $"2026 {suffix}",
            AcademicYear = "2026-2027",
            Season = TermSeason.Autumn,
            StartDate = new DateOnly(2026, 9, 1),
            EndDate = new DateOnly(2027, 1, 15)
        };
        var campus = new Campus { Code = $"C-{suffix}", Name = "主校区" };
        var college = new College
        {
            Code = $"COL-{suffix}",
            Name = "计算机学院",
            CampusId = campus.Id
        };
        var building = new Building
        {
            Code = $"B-{suffix}",
            Name = "第一教学楼",
            CampusId = campus.Id
        };
        var classroom = new Classroom
        {
            Code = $"R-{suffix}",
            Name = "101",
            BuildingId = building.Id,
            Capacity = 80
        };
        var smallClassroom = new Classroom
        {
            Code = $"R-SMALL-{suffix}",
            Name = "102",
            BuildingId = building.Id,
            Capacity = 1
        };
        var major = new Major
        {
            Code = $"MAJOR-{suffix}",
            Name = "计算机科学与技术",
            CollegeId = college.Id,
            DegreeType = "工学学士"
        };
        var administrativeClass = new AdministrativeClass
        {
            Code = $"CLASS-{suffix}",
            Name = "计科 2026-1 班",
            MajorId = major.Id,
            Grade = 2026
        };
        var secondAdministrativeClass = new AdministrativeClass
        {
            Code = $"CLASS-2-{suffix}",
            Name = "计科 2026-2 班",
            MajorId = major.Id,
            Grade = 2026
        };
        var firstCourse = new Course
        {
            Code = $"COURSE-1-{suffix}",
            Name = "程序设计",
            CollegeId = college.Id
        };
        var secondCourse = new Course
        {
            Code = $"COURSE-2-{suffix}",
            Name = "大学英语",
            CollegeId = college.Id
        };
        var firstTask = new TeachingTask
        {
            TaskNumber = $"TASK-1-{suffix}",
            Name = "程序设计教学班",
            AcademicTermId = term.Id,
            CourseId = firstCourse.Id,
            Status = TeachingTaskStatus.Published,
            Classes =
            [
                new TeachingTaskClass
                {
                    AdministrativeClassId = administrativeClass.Id
                }
            ]
        };
        var secondTask = new TeachingTask
        {
            TaskNumber = $"TASK-2-{suffix}",
            Name = "大学英语教学班",
            AcademicTermId = term.Id,
            CourseId = secondCourse.Id,
            Status = TeachingTaskStatus.Published
        };
        var sameCourseTask = new TeachingTask
        {
            TaskNumber = $"TASK-3-{suffix}",
            Name = "程序设计第二教学班",
            AcademicTermId = term.Id,
            CourseId = firstCourse.Id,
            Status = TeachingTaskStatus.Published,
            Classes =
            [
                new TeachingTaskClass
                {
                    AdministrativeClassId = secondAdministrativeClass.Id
                }
            ]
        };
        var invigilator = new Teacher
        {
            TeacherNumber = $"INVIGILATOR-{suffix}",
            Name = "监考教师",
            CollegeId = college.Id,
            Status = TeacherStatus.Active
        };

        db.AddRange(
            term,
            campus,
            college,
            building,
            classroom,
            smallClassroom,
            major,
            administrativeClass,
            secondAdministrativeClass,
            new Student
            {
                StudentNumber = $"STUDENT-1-{suffix}",
                Name = "学生甲",
                AdministrativeClassId = administrativeClass.Id,
                EnrollmentYear = 2026,
                EnrollmentDate = new DateOnly(2026, 9, 1)
            },
            new Student
            {
                StudentNumber = $"STUDENT-2-{suffix}",
                Name = "学生乙",
                AdministrativeClassId = administrativeClass.Id,
                EnrollmentYear = 2026,
                EnrollmentDate = new DateOnly(2026, 9, 1)
            },
            new Student
            {
                StudentNumber = $"STUDENT-3-{suffix}",
                Name = "学生丙",
                AdministrativeClassId = administrativeClass.Id,
                EnrollmentYear = 2026,
                EnrollmentDate = new DateOnly(2026, 9, 1)
            },
            new Student
            {
                StudentNumber = $"STUDENT-4-{suffix}",
                Name = "学生丁",
                AdministrativeClassId = secondAdministrativeClass.Id,
                EnrollmentYear = 2026,
                EnrollmentDate = new DateOnly(2026, 9, 1)
            },
            new Student
            {
                StudentNumber = $"STUDENT-5-{suffix}",
                Name = "学生戊",
                AdministrativeClassId = secondAdministrativeClass.Id,
                EnrollmentYear = 2026,
                EnrollmentDate = new DateOnly(2026, 9, 1)
            },
            new Student
            {
                StudentNumber = $"STUDENT-6-{suffix}",
                Name = "学生己",
                AdministrativeClassId = secondAdministrativeClass.Id,
                EnrollmentYear = 2026,
                EnrollmentDate = new DateOnly(2026, 9, 1)
            },
            firstCourse,
            secondCourse,
            firstTask,
            secondTask,
            sameCourseTask,
            invigilator,
            new ScheduleTimeSlot
            {
                AcademicTermId = term.Id,
                PeriodNumber = 1,
                Name = "第1节",
                StartsAt = new TimeOnly(8, 0),
                EndsAt = new TimeOnly(8, 45)
            },
            new ScheduleTimeSlot
            {
                AcademicTermId = term.Id,
                PeriodNumber = 2,
                Name = "第2节",
                StartsAt = new TimeOnly(9, 0),
                EndsAt = new TimeOnly(9, 50)
            });
        await db.SaveChangesAsync();
        return new SeedData(
            term,
            firstTask,
            secondTask,
            sameCourseTask,
            classroom,
            smallClassroom);
    }

    private sealed record SeedData(
        AcademicTerm Term,
        TeachingTask FirstTask,
        TeachingTask SecondTask,
        TeachingTask SameCourseTask,
        Classroom LargeClassroom,
        Classroom SmallClassroom);
}
