using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Common;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

namespace Jiaowu.Api.Infrastructure.Persistence;

public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
    : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>(options)
{
    public DbSet<Campus> Campuses => Set<Campus>();
    public DbSet<College> Colleges => Set<College>();
    public DbSet<Major> Majors => Set<Major>();
    public DbSet<AdministrativeClass> AdministrativeClasses => Set<AdministrativeClass>();
    public DbSet<Building> Buildings => Set<Building>();
    public DbSet<Classroom> Classrooms => Set<Classroom>();
    public DbSet<AcademicTerm> AcademicTerms => Set<AcademicTerm>();
    public DbSet<Teacher> Teachers => Set<Teacher>();
    public DbSet<Student> Students => Set<Student>();
    public DbSet<CourseCategory> CourseCategories => Set<CourseCategory>();
    public DbSet<Course> Courses => Set<Course>();
    public DbSet<CoursePrerequisite> CoursePrerequisites => Set<CoursePrerequisite>();
    public DbSet<CurriculumPlan> CurriculumPlans => Set<CurriculumPlan>();
    public DbSet<CurriculumModule> CurriculumModules => Set<CurriculumModule>();
    public DbSet<CurriculumCourse> CurriculumCourses => Set<CurriculumCourse>();
    public DbSet<CourseGroup> CourseGroups => Set<CourseGroup>();
    public DbSet<CourseGroupCourse> CourseGroupCourses => Set<CourseGroupCourse>();
    public DbSet<TeachingTask> TeachingTasks => Set<TeachingTask>();
    public DbSet<TeachingTaskTeacher> TeachingTaskTeachers => Set<TeachingTaskTeacher>();
    public DbSet<TeachingTaskClass> TeachingTaskClasses => Set<TeachingTaskClass>();
    public DbSet<TeacherCourseApplication> TeacherCourseApplications =>
        Set<TeacherCourseApplication>();
    public DbSet<SchedulePlan> SchedulePlans => Set<SchedulePlan>();
    public DbSet<ScheduleEntry> ScheduleEntries => Set<ScheduleEntry>();
    public DbSet<PublishedScheduleOccurrence> PublishedScheduleOccurrences => Set<PublishedScheduleOccurrence>();
    public DbSet<ScheduleTimeSlot> ScheduleTimeSlots => Set<ScheduleTimeSlot>();
    public DbSet<TeachingTaskScheduleConstraint> TeachingTaskScheduleConstraints =>
        Set<TeachingTaskScheduleConstraint>();
    public DbSet<TeachingTaskAllowedClassroom> TeachingTaskAllowedClassrooms =>
        Set<TeachingTaskAllowedClassroom>();
    public DbSet<TeachingTaskAllowedExperimentClassroom> TeachingTaskAllowedExperimentClassrooms =>
        Set<TeachingTaskAllowedExperimentClassroom>();
    public DbSet<AutomaticScheduleJob> AutomaticScheduleJobs =>
        Set<AutomaticScheduleJob>();
    public DbSet<SchedulePublishJob> SchedulePublishJobs =>
        Set<SchedulePublishJob>();
    public DbSet<ClassroomReservation> ClassroomReservations =>
        Set<ClassroomReservation>();
    public DbSet<ExperimentProject> ExperimentProjects => Set<ExperimentProject>();
    public DbSet<ExperimentSession> ExperimentSessions => Set<ExperimentSession>();
    public DbSet<ExperimentSessionInstructor> ExperimentSessionInstructors =>
        Set<ExperimentSessionInstructor>();
    public DbSet<ExperimentBooking> ExperimentBookings => Set<ExperimentBooking>();
    public DbSet<ExperimentGradeSheet> ExperimentGradeSheets =>
        Set<ExperimentGradeSheet>();
    public DbSet<ExperimentGradeItem> ExperimentGradeItems =>
        Set<ExperimentGradeItem>();
    public DbSet<ExperimentGradeRecord> ExperimentGradeRecords =>
        Set<ExperimentGradeRecord>();
    public DbSet<ExperimentCourseGrade> ExperimentCourseGrades =>
        Set<ExperimentCourseGrade>();
    public DbSet<ExperimentGradeItemScore> ExperimentGradeItemScores =>
        Set<ExperimentGradeItemScore>();
    public DbSet<CourseSelectionRound> CourseSelectionRounds =>
        Set<CourseSelectionRound>();
    public DbSet<CourseSelectionRoundGrade> CourseSelectionRoundGrades =>
        Set<CourseSelectionRoundGrade>();
    public DbSet<CourseSelectionOffering> CourseSelectionOfferings =>
        Set<CourseSelectionOffering>();
    public DbSet<CourseEnrollment> CourseEnrollments => Set<CourseEnrollment>();
    public DbSet<GradeSheet> GradeSheets => Set<GradeSheet>();
    public DbSet<GradeRecord> GradeRecords => Set<GradeRecord>();
    public DbSet<GradeItem> GradeItems => Set<GradeItem>();
    public DbSet<GradeItemScore> GradeItemScores => Set<GradeItemScore>();
    public DbSet<CourseGradeStatistic> CourseGradeStatistics =>
        Set<CourseGradeStatistic>();
    public DbSet<TeachingTaskGradeStatistic> TeachingTaskGradeStatistics =>
        Set<TeachingTaskGradeStatistic>();
    public DbSet<TeachingTaskGradeScoreBand> TeachingTaskGradeScoreBands =>
        Set<TeachingTaskGradeScoreBand>();
    public DbSet<CourseGradeStatisticsRefreshJob> CourseGradeStatisticsRefreshJobs =>
        Set<CourseGradeStatisticsRefreshJob>();
    public DbSet<OtherExamBatch> OtherExamBatches => Set<OtherExamBatch>();
    public DbSet<OtherExamResult> OtherExamResults => Set<OtherExamResult>();
    public DbSet<AttendanceSheet> AttendanceSheets => Set<AttendanceSheet>();
    public DbSet<AttendanceRecord> AttendanceRecords => Set<AttendanceRecord>();
    public DbSet<AttendanceCheckInAttempt> AttendanceCheckInAttempts =>
        Set<AttendanceCheckInAttempt>();
    public DbSet<ExamPlan> ExamPlans => Set<ExamPlan>();
    public DbSet<ExamArrangementJob> ExamArrangementJobs =>
        Set<ExamArrangementJob>();
    public DbSet<ExamSignInExportJob> ExamSignInExportJobs =>
        Set<ExamSignInExportJob>();
    public DbSet<ExamPublishJob> ExamPublishJobs =>
        Set<ExamPublishJob>();
    public DbSet<ExamSession> ExamSessions => Set<ExamSession>();
    public DbSet<ExamSessionInvigilator> ExamSessionInvigilators =>
        Set<ExamSessionInvigilator>();
    public DbSet<ExamRoomAssignment> ExamRooms => Set<ExamRoomAssignment>();
    public DbSet<ExamRoomSession> ExamRoomSessions => Set<ExamRoomSession>();
    public DbSet<ExamSeatAssignment> ExamSeats => Set<ExamSeatAssignment>();
    public DbSet<ExamRoomInvigilator> ExamRoomInvigilators =>
        Set<ExamRoomInvigilator>();
    public DbSet<MakeupExamPlan> MakeupExamPlans => Set<MakeupExamPlan>();
    public DbSet<MakeupExamSession> MakeupExamSessions => Set<MakeupExamSession>();
    public DbSet<MakeupExamSessionInvigilator> MakeupExamSessionInvigilators =>
        Set<MakeupExamSessionInvigilator>();
    public DbSet<MakeupExamEnrollment> MakeupExamEnrollments =>
        Set<MakeupExamEnrollment>();
    public DbSet<MakeupExamAutoJob> MakeupExamAutoJobs => Set<MakeupExamAutoJob>();
    public DbSet<CourseAdjustment> CourseAdjustments => Set<CourseAdjustment>();
    public DbSet<CourseExemption> CourseExemptions => Set<CourseExemption>();
    public DbSet<DeferredExam> DeferredExams => Set<DeferredExam>();
    public DbSet<GradeModification> GradeModifications => Set<GradeModification>();
    public DbSet<CourseSubstitution> CourseSubstitutions => Set<CourseSubstitution>();
    public DbSet<WarningRule> WarningRules => Set<WarningRule>();
    public DbSet<WarningRecord> WarningRecords => Set<WarningRecord>();
    public DbSet<EvaluationSetup> EvaluationSetups => Set<EvaluationSetup>();
    public DbSet<EvaluationDimension> EvaluationDimensions => Set<EvaluationDimension>();
    public DbSet<EvaluationRecord> EvaluationRecords => Set<EvaluationRecord>();
    public DbSet<EvaluationScore> EvaluationScores => Set<EvaluationScore>();
    public DbSet<Notification> Notifications => Set<Notification>();
    public DbSet<MessageDispatch> MessageDispatches => Set<MessageDispatch>();
    public DbSet<StudentStatusChange> StudentStatusChanges =>
        Set<StudentStatusChange>();
    public DbSet<GraduationAuditBatch> GraduationAuditBatches =>
        Set<GraduationAuditBatch>();
    public DbSet<GraduationAuditResult> GraduationAuditResults =>
        Set<GraduationAuditResult>();
    public DbSet<DegreeAwardBatch> DegreeAwardBatches => Set<DegreeAwardBatch>();
    public DbSet<DegreeAwardResult> DegreeAwardResults => Set<DegreeAwardResult>();
    public DbSet<GraduationClearanceBatch> GraduationClearanceBatches =>
        Set<GraduationClearanceBatch>();
    public DbSet<GraduationClearanceItem> GraduationClearanceItems =>
        Set<GraduationClearanceItem>();
    public DbSet<GraduationClearanceRecord> GraduationClearanceRecords =>
        Set<GraduationClearanceRecord>();
    public DbSet<OfficialDocument> OfficialDocuments => Set<OfficialDocument>();
    public DbSet<OfficialDocumentDownload> OfficialDocumentDownloads =>
        Set<OfficialDocumentDownload>();
    public DbSet<AuditLog> AuditLogs => Set<AuditLog>();
    public DbSet<BackgroundJobOutboxMessage> BackgroundJobOutboxMessages =>
        Set<BackgroundJobOutboxMessage>();
    public DbSet<AppUpdateRelease> AppUpdateReleases =>
        Set<AppUpdateRelease>();
    public DbSet<SystemFeatureSetting> SystemFeatureSettings =>
        Set<SystemFeatureSetting>();
    public DbSet<CourseGradeStatisticsRefreshSetting> CourseGradeStatisticsRefreshSettings =>
        Set<CourseGradeStatisticsRefreshSetting>();
    public DbSet<RefreshSession> RefreshSessions => Set<RefreshSession>();

    protected override void ConfigureConventions(
        ModelConfigurationBuilder configurationBuilder)
    {
        base.ConfigureConventions(configurationBuilder);

        // Connector/NET returns MySQL DATE values as DateTime. An explicit
        // provider conversion prevents EF from asking the reader for DateOnly.
        configurationBuilder.Properties<DateOnly>()
            .HaveConversion<DateOnlyDateTimeConverter>()
            .HaveColumnType("date");

        // Connector/NET returns MySQL TIME values as TimeSpan. Convert at the
        // provider boundary so schedule time slots can still use TimeOnly.
        configurationBuilder.Properties<TimeOnly>()
            .HaveConversion<TimeOnlyTimeSpanConverter>()
            .HaveColumnType("time");

        // MySQL DATETIME has no offset or DateTimeKind. All system timestamps
        // are persisted as UTC, so restore that contract when materializing
        // them. System.Text.Json will then emit the trailing "Z", allowing
        // browsers to convert timestamps to the viewer's local time correctly.
        configurationBuilder.Properties<DateTime>()
            .HaveConversion<UtcDateTimeConverter>()
            .HaveColumnType("datetime(6)");
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<ApplicationUser>(entity =>
        {
            entity.Property(x => x.DisplayName).HasMaxLength(50);
            entity.Property(x => x.StaffNumber).HasMaxLength(30);
            entity.Property(x => x.CalendarSubscriptionStamp).HasMaxLength(64);
            entity.HasIndex(x => x.StaffNumber);
        });

        builder.Entity<ApplicationRole>(entity =>
        {
            entity.Property(x => x.Description).HasMaxLength(100);
        });

        builder.Entity<RefreshSession>(entity =>
        {
            entity.Property(x => x.TokenHash).HasMaxLength(64);
            entity.Property(x => x.SecurityStamp).HasMaxLength(100);
            entity.Property(x => x.ClientType)
                .HasConversion<string>()
                .HasMaxLength(20);
            entity.HasIndex(x => x.TokenHash).IsUnique();
            entity.HasIndex(x => new { x.UserId, x.ExpiresAt });
            entity.HasOne(x => x.User)
                .WithMany()
                .HasForeignKey(x => x.UserId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        ConfigureCatalog<Campus>(builder);
        ConfigureCatalog<College>(builder);
        ConfigureCatalog<Major>(builder);
        ConfigureCatalog<AdministrativeClass>(builder);
        ConfigureCatalog<Building>(builder);
        ConfigureCatalog<Classroom>(builder);
        ConfigureCatalog<AcademicTerm>(builder);
        ConfigureCatalog<CourseCategory>(builder);
        ConfigureCatalog<Course>(builder);

        builder.Entity<College>()
            .HasOne(x => x.Campus)
            .WithMany()
            .HasForeignKey(x => x.CampusId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.Entity<Major>()
            .HasOne(x => x.College)
            .WithMany()
            .HasForeignKey(x => x.CollegeId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.Entity<AdministrativeClass>()
            .HasOne(x => x.Major)
            .WithMany()
            .HasForeignKey(x => x.MajorId)
            .OnDelete(DeleteBehavior.Restrict);
        builder.Entity<AdministrativeClass>(entity =>
        {
            entity.HasIndex(x => x.CounselorUserId);
            entity.HasOne(x => x.CounselorUser)
                .WithMany()
                .HasForeignKey(x => x.CounselorUserId)
                .OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<Building>()
            .HasOne(x => x.Campus)
            .WithMany()
            .HasForeignKey(x => x.CampusId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.Entity<Classroom>()
            .HasOne(x => x.Building)
            .WithMany()
            .HasForeignKey(x => x.BuildingId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.Entity<AcademicTerm>(entity =>
        {
            entity.HasIndex(x => x.IsCurrent);
            entity.HasIndex(x => x.IsArchived);
        });

        builder.Entity<Teacher>(entity =>
        {
            entity.Property(x => x.TeacherNumber).HasMaxLength(30);
            entity.Property(x => x.Name).HasMaxLength(50);
            entity.Property(x => x.Title).HasMaxLength(30);
            entity.Property(x => x.Phone).HasMaxLength(30);
            entity.Property(x => x.Email).HasMaxLength(100);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => x.TeacherNumber).IsUnique();
            entity.HasIndex(x => new { x.CollegeId, x.Status });
            entity.HasOne(x => x.College)
                .WithMany()
                .HasForeignKey(x => x.CollegeId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne<ApplicationUser>()
                .WithMany()
                .HasForeignKey(x => x.UserId)
                .OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<Student>(entity =>
        {
            entity.Property(x => x.StudentNumber).HasMaxLength(30);
            entity.Property(x => x.Name).HasMaxLength(50);
            entity.Property(x => x.EnglishName).HasMaxLength(100);
            entity.Property(x => x.IdCardNumber).HasMaxLength(30);
            entity.Property(x => x.Nationality).HasMaxLength(50);
            entity.Property(x => x.Ethnicity).HasMaxLength(50);
            entity.Property(x => x.PoliticalStatus).HasMaxLength(50);
            entity.Property(x => x.NativePlace).HasMaxLength(100);
            entity.Property(x => x.HouseholdAddress).HasMaxLength(300);
            entity.Property(x => x.CurrentAddress).HasMaxLength(300);
            entity.Property(x => x.PostalCode).HasMaxLength(20);
            entity.Property(x => x.Phone).HasMaxLength(30);
            entity.Property(x => x.Email).HasMaxLength(100);
            entity.Property(x => x.Qq).HasMaxLength(30);
            entity.Property(x => x.WeChat).HasMaxLength(60);
            entity.Property(x => x.EmergencyContactName).HasMaxLength(50);
            entity.Property(x => x.EmergencyContactRelationship).HasMaxLength(30);
            entity.Property(x => x.EmergencyContactPhone).HasMaxLength(30);
            entity.Property(x => x.SpecialTags).HasMaxLength(300);
            entity.Property(x => x.SpecialNeeds).HasMaxLength(1000);
            entity.Property(x => x.Biography).HasMaxLength(1000);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => x.StudentNumber).IsUnique();
            entity.HasIndex(x => new { x.AdministrativeClassId, x.Status });
            entity.HasIndex(x => x.EnrollmentYear);
            entity.HasOne(x => x.AdministrativeClass)
                .WithMany(x => x.Students)
                .HasForeignKey(x => x.AdministrativeClassId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne<ApplicationUser>()
                .WithMany()
                .HasForeignKey(x => x.UserId)
                .OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<Course>(entity =>
        {
            entity.Property(x => x.EnglishName).HasMaxLength(150);
            entity.Property(x => x.Credits).HasPrecision(5, 2);
            entity.Property(x => x.Description).HasMaxLength(1000);
            entity.HasIndex(x => new { x.CollegeId, x.Nature });
            entity.HasIndex(x => x.CourseCategoryId);
            entity.HasOne(x => x.College)
                .WithMany()
                .HasForeignKey(x => x.CollegeId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.CourseCategory)
                .WithMany()
                .HasForeignKey(x => x.CourseCategoryId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CoursePrerequisite>(entity =>
        {
            entity.HasIndex(x => new { x.CourseId, x.PrerequisiteCourseId })
                .IsUnique();
            entity.HasOne(x => x.Course)
                .WithMany(x => x.Prerequisites)
                .HasForeignKey(x => x.CourseId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.PrerequisiteCourse)
                .WithMany(x => x.RequiredByCourses)
                .HasForeignKey(x => x.PrerequisiteCourseId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CurriculumPlan>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.Version).HasMaxLength(30);
            entity.Property(x => x.TotalCredits).HasPrecision(6, 2);
            entity.Property(x => x.Description).HasMaxLength(1000);
            entity.HasIndex(x => new { x.MajorId, x.EffectiveGrade, x.Version }).IsUnique();
            entity.HasIndex(x => new { x.Status, x.EffectiveGrade });
            entity.HasOne(x => x.Major)
                .WithMany()
                .HasForeignKey(x => x.MajorId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CurriculumModule>(entity =>
        {
            entity.Property(x => x.Code).HasMaxLength(30);
            entity.Property(x => x.Name).HasMaxLength(100);
            entity.Property(x => x.RequiredCredits).HasPrecision(6, 2);
            entity.HasIndex(x => new { x.CurriculumPlanId, x.Code }).IsUnique();
            entity.HasOne(x => x.CurriculumPlan)
                .WithMany(x => x.Modules)
                .HasForeignKey(x => x.CurriculumPlanId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<CurriculumCourse>(entity =>
        {
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.CurriculumModuleId, x.CourseId }).IsUnique();
            entity.HasOne(x => x.CurriculumModule)
                .WithMany(x => x.Courses)
                .HasForeignKey(x => x.CurriculumModuleId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Course)
                .WithMany()
                .HasForeignKey(x => x.CourseId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<TeachingTask>(entity =>
        {
            entity.Property(x => x.TaskNumber).HasMaxLength(40);
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.GenerationBatchCode).HasMaxLength(40);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => x.TaskNumber).IsUnique();
            entity.HasIndex(x => new { x.AcademicTermId, x.Status });
            entity.HasOne(x => x.AcademicTerm)
                .WithMany()
                .HasForeignKey(x => x.AcademicTermId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Course)
                .WithMany()
                .HasForeignKey(x => x.CourseId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<TeachingTaskTeacher>(entity =>
        {
            entity.HasKey(x => new { x.TeachingTaskId, x.TeacherId });
            entity.HasOne(x => x.TeachingTask)
                .WithMany(x => x.Teachers)
                .HasForeignKey(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Teacher)
                .WithMany()
                .HasForeignKey(x => x.TeacherId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<TeachingTaskClass>(entity =>
        {
            entity.HasKey(x => new { x.TeachingTaskId, x.AdministrativeClassId });
            entity.HasOne(x => x.TeachingTask)
                .WithMany(x => x.Classes)
                .HasForeignKey(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.AdministrativeClass)
                .WithMany()
                .HasForeignKey(x => x.AdministrativeClassId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<TeacherCourseApplication>(entity =>
        {
            entity.Property(x => x.Statement).HasMaxLength(500);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new
            {
                x.AcademicTermId,
                x.TeacherId,
                x.CourseId
            }).IsUnique();
            entity.HasIndex(x => new { x.Status, x.AcademicTermId });
            entity.HasOne(x => x.AcademicTerm)
                .WithMany()
                .HasForeignKey(x => x.AcademicTermId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Teacher)
                .WithMany()
                .HasForeignKey(x => x.TeacherId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Course)
                .WithMany()
                .HasForeignKey(x => x.CourseId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne<ApplicationUser>()
                .WithMany()
                .HasForeignKey(x => x.ReviewedByUserId)
                .OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<SchedulePlan>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.Version).HasMaxLength(30);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.AcademicTermId, x.Version }).IsUnique();
            entity.HasIndex(x => new { x.AcademicTermId, x.Status });
            entity.HasOne(x => x.AcademicTerm)
                .WithMany()
                .HasForeignKey(x => x.AcademicTermId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<ScheduleEntry>(entity =>
        {
            entity.Property(x => x.Kind)
                .HasDefaultValue(ScheduleEntryKind.Lecture)
                .HasSentinel((ScheduleEntryKind)0);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new
            {
                x.SchedulePlanId,
                x.DayOfWeek,
                x.StartPeriod
            });
            entity.HasOne(x => x.SchedulePlan)
                .WithMany(x => x.Entries)
                .HasForeignKey(x => x.SchedulePlanId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.TeachingTask)
                .WithMany()
                .HasForeignKey(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Classroom)
                .WithMany()
                .HasForeignKey(x => x.ClassroomId)
                .OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<ScheduleTimeSlot>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(40);
            entity.HasIndex(x => new { x.AcademicTermId, x.PeriodNumber }).IsUnique();
            entity.HasOne(x => x.AcademicTerm)
                .WithMany()
                .HasForeignKey(x => x.AcademicTermId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<TeachingTaskScheduleConstraint>(entity =>
        {
            entity.Property(x => x.AllowedDayOfWeeks).HasMaxLength(20);
            entity.HasIndex(x => x.TeachingTaskId).IsUnique();
            entity.HasOne(x => x.TeachingTask)
                .WithMany()
                .HasForeignKey(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.RequiredCampus)
                .WithMany()
                .HasForeignKey(x => x.RequiredCampusId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.RequiredBuilding)
                .WithMany()
                .HasForeignKey(x => x.RequiredBuildingId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.ExperimentRequiredCampus)
                .WithMany()
                .HasForeignKey(x => x.ExperimentRequiredCampusId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.ExperimentRequiredBuilding)
                .WithMany()
                .HasForeignKey(x => x.ExperimentRequiredBuildingId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<TeachingTaskAllowedClassroom>(entity =>
        {
            entity.HasKey(x => new
            {
                x.TeachingTaskScheduleConstraintId,
                x.ClassroomId
            });
            entity.HasOne(x => x.TeachingTaskScheduleConstraint)
                .WithMany(x => x.AllowedClassrooms)
                .HasForeignKey(x => x.TeachingTaskScheduleConstraintId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Classroom)
                .WithMany()
                .HasForeignKey(x => x.ClassroomId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CourseGroup>(entity =>
        {
            entity.Property(x => x.Code).HasMaxLength(30);
            entity.Property(x => x.Name).HasMaxLength(100);
            entity.Property(x => x.Description).HasMaxLength(500);
            entity.HasIndex(x => x.Code).IsUnique();
        });

        builder.Entity<CourseGroupCourse>(entity =>
        {
            entity.HasIndex(x => new { x.CourseGroupId, x.CourseId }).IsUnique();
            entity.HasOne(x => x.CourseGroup)
                .WithMany(x => x.Courses)
                .HasForeignKey(x => x.CourseGroupId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Course)
                .WithMany()
                .HasForeignKey(x => x.CourseId)
                .OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<PublishedScheduleOccurrence>(entity =>
        {
            entity.HasIndex(x => new { x.AcademicTermId, x.TeachingTaskId, x.Week });
            entity.HasIndex(x => new
            {
                x.AcademicTermId,
                x.Week,
                x.DayOfWeek,
                x.StartPeriod,
                x.ClassroomId
            });
            entity.HasIndex(x => new { x.SchedulePlanId, x.ClassroomId, x.Week, x.DayOfWeek, x.StartPeriod });
            entity.HasIndex(x => new { x.ScheduleEntryId, x.Week }).IsUnique();
            entity.HasOne(x => x.ScheduleEntry).WithMany().HasForeignKey(x => x.ScheduleEntryId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.TeachingTask).WithMany().HasForeignKey(x => x.TeachingTaskId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Classroom).WithMany().HasForeignKey(x => x.ClassroomId).OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<TeachingTaskAllowedExperimentClassroom>(entity =>
        {
            entity.HasKey(x => new { x.TeachingTaskScheduleConstraintId, x.ClassroomId });
            entity.HasOne(x => x.TeachingTaskScheduleConstraint)
                .WithMany(x => x.AllowedExperimentClassrooms)
                .HasForeignKey(x => x.TeachingTaskScheduleConstraintId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Classroom)
                .WithMany()
                .HasForeignKey(x => x.ClassroomId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<AutomaticScheduleJob>(entity =>
        {
            entity.Property(x => x.ErrorMessage).HasMaxLength(2000);
            entity.HasIndex(x => x.ActiveSchedulePlanId).IsUnique();
            entity.HasIndex(x => new { x.SchedulePlanId, x.CreatedAt });
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasIndex(x => x.RequestedByUserId);
            entity.HasOne(x => x.SchedulePlan)
                .WithMany()
                .HasForeignKey(x => x.SchedulePlanId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne<ApplicationUser>()
                .WithMany()
                .HasForeignKey(x => x.RequestedByUserId)
                .OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<SchedulePublishJob>(entity =>
        {
            entity.Property(x => x.CurrentStep).HasMaxLength(200);
            entity.Property(x => x.ErrorMessage).HasMaxLength(2000);
            entity.HasIndex(x => x.ActiveAcademicTermId).IsUnique();
            entity.HasIndex(x => new { x.SchedulePlanId, x.CreatedAt });
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasIndex(x => x.RequestedByUserId);
            entity.HasOne(x => x.SchedulePlan)
                .WithMany()
                .HasForeignKey(x => x.SchedulePlanId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne<ApplicationUser>()
                .WithMany()
                .HasForeignKey(x => x.RequestedByUserId)
                .OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<ClassroomReservation>(entity =>
        {
            entity.Property(x => x.ApplicantName).HasMaxLength(50);
            entity.Property(x => x.Purpose).HasMaxLength(200);
            entity.Property(x => x.ContactPhone).HasMaxLength(30);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new { x.ApplicantUserId, x.Status, x.CreatedAt });
            entity.HasIndex(x => new
            {
                x.ApplicantCollegeId,
                x.Status,
                x.ReservationDate
            });
            entity.HasIndex(x => new
            {
                x.ClassroomId,
                x.ReservationDate,
                x.Status,
                x.StartPeriod
            });
            entity.HasOne(x => x.ApplicantUser)
                .WithMany()
                .HasForeignKey(x => x.ApplicantUserId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.ApplicantCollege)
                .WithMany()
                .HasForeignKey(x => x.ApplicantCollegeId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.AcademicTerm)
                .WithMany()
                .HasForeignKey(x => x.AcademicTermId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Classroom)
                .WithMany()
                .HasForeignKey(x => x.ClassroomId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.ReviewedByUser)
                .WithMany()
                .HasForeignKey(x => x.ReviewedByUserId)
                .OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<ExperimentProject>(entity =>
        {
            entity.Property(x => x.Code).HasMaxLength(40);
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.Description).HasMaxLength(1000);
            entity.Property(x => x.Requirements).HasMaxLength(1000);
            entity.Property(x => x.SelectionStartsAt).HasConversion<UtcDateTimeConverter>();
            entity.Property(x => x.SelectionEndsAt).HasConversion<UtcDateTimeConverter>();
            // 集中安排会为同一教学任务的每一条实验课表记录生成项目；
            // 自行安排仍由控制器保持“教学任务 + 编码”唯一。
            entity.HasIndex(x => new
            {
                x.TeachingTaskId,
                x.Code,
                x.ScheduleEntryId,
                x.ScheduleWeek
            })
                .IsUnique();
            entity.HasIndex(x => new { x.Status, x.StartDate, x.EndDate });
            entity.HasOne(x => x.TeachingTask).WithMany()
                .HasForeignKey(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasIndex(x => x.ScheduleEntryId);
            entity.HasOne(x => x.ScheduleEntry).WithMany()
                .HasForeignKey(x => x.ScheduleEntryId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<ExperimentSession>(entity =>
        {
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new
            {
                x.ExperimentProjectId,
                x.SessionDate,
                x.StartPeriod
            });
            entity.HasIndex(x => new
            {
                x.ClassroomId,
                x.SessionDate,
                x.Status,
                x.StartPeriod
            });
            entity.HasOne(x => x.ExperimentProject).WithMany(x => x.Sessions)
                .HasForeignKey(x => x.ExperimentProjectId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Classroom).WithMany()
                .HasForeignKey(x => x.ClassroomId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<ExperimentBooking>(entity =>
        {
            entity.HasIndex(x => new { x.ExperimentProjectId, x.StudentId })
                .IsUnique();
            entity.HasIndex(x => new
            {
                x.ExperimentSessionId,
                x.Status,
                x.BookedAt
            });
            entity.HasOne(x => x.ExperimentProject).WithMany(x => x.Bookings)
                .HasForeignKey(x => x.ExperimentProjectId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.ExperimentSession).WithMany(x => x.Bookings)
                .HasForeignKey(x => x.ExperimentSessionId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<ExperimentGradeSheet>(entity =>
        {
            entity.Property(x => x.ContributionWeight).HasPrecision(5, 1);
            entity.Property(x => x.PassScore).HasPrecision(5, 1);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => x.ExperimentProjectId).IsUnique();
            entity.HasOne(x => x.ExperimentProject)
                .WithOne(x => x.GradeSheet)
                .HasForeignKey<ExperimentGradeSheet>(
                    x => x.ExperimentProjectId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<ExperimentGradeItem>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(60);
            entity.Property(x => x.Weight).HasPrecision(5, 1);
            entity.HasIndex(x => new
            {
                x.ExperimentGradeSheetId,
                x.SortOrder
            });
            entity.HasOne(x => x.ExperimentGradeSheet)
                .WithMany(x => x.Items)
                .HasForeignKey(x => x.ExperimentGradeSheetId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<ExperimentGradeRecord>(entity =>
        {
            entity.Property(x => x.TotalScore).HasPrecision(5, 1);
            entity.Property(x => x.SubmissionReference).HasMaxLength(500);
            entity.Property(x => x.TeacherComment).HasMaxLength(500);
            entity.HasIndex(x => new
            {
                x.ExperimentGradeSheetId,
                x.StudentId
            }).IsUnique();
            entity.HasOne(x => x.ExperimentGradeSheet)
                .WithMany(x => x.Records)
                .HasForeignKey(x => x.ExperimentGradeSheetId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.ExperimentSession).WithMany()
                .HasForeignKey(x => x.ExperimentSessionId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<ExperimentSessionInstructor>(entity =>
        {
            entity.HasIndex(x => new { x.ExperimentSessionId, x.TeacherId })
                .IsUnique();
            entity.HasIndex(x => x.TeacherId);
            entity.HasOne(x => x.ExperimentSession).WithMany(x => x.Instructors)
                .HasForeignKey(x => x.ExperimentSessionId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Teacher).WithMany()
                .HasForeignKey(x => x.TeacherId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<ExperimentCourseGrade>(entity =>
        {
            entity.Property(x => x.WeightedAverageScore).HasPrecision(5, 1);
            entity.Property(x => x.TotalWeight).HasPrecision(8, 1);
            entity.HasIndex(x => new { x.TeachingTaskId, x.StudentId })
                .IsUnique();
            entity.HasIndex(x => x.StudentId);
            entity.HasOne(x => x.TeachingTask).WithMany()
                .HasForeignKey(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<ExperimentGradeItemScore>(entity =>
        {
            entity.HasKey(x => new
            {
                x.ExperimentGradeRecordId,
                x.ExperimentGradeItemId
            });
            entity.Property(x => x.Score).HasPrecision(5, 1);
            entity.Property(x => x.Comment).HasMaxLength(300);
            entity.HasOne(x => x.ExperimentGradeRecord)
                .WithMany(x => x.ItemScores)
                .HasForeignKey(x => x.ExperimentGradeRecordId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.ExperimentGradeItem)
                .WithMany(x => x.Scores)
                .HasForeignKey(x => x.ExperimentGradeItemId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<CourseSelectionRound>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.MaxCredits).HasPrecision(6, 1);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.AcademicTermId, x.Status });
            entity.HasOne(x => x.AcademicTerm)
                .WithMany()
                .HasForeignKey(x => x.AcademicTermId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CourseSelectionRoundGrade>(entity =>
        {
            entity.HasIndex(x => new { x.CourseSelectionRoundId, x.Grade })
                .IsUnique();
            entity.HasIndex(x => x.Grade);
            entity.HasOne(x => x.CourseSelectionRound)
                .WithMany(x => x.EligibleGrades)
                .HasForeignKey(x => x.CourseSelectionRoundId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<CourseSelectionOffering>(entity =>
        {
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new
            {
                x.CourseSelectionRoundId,
                x.TeachingTaskId
            }).IsUnique();
            entity.HasOne(x => x.CourseSelectionRound)
                .WithMany(x => x.Offerings)
                .HasForeignKey(x => x.CourseSelectionRoundId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.TeachingTask)
                .WithMany()
                .HasForeignKey(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CourseEnrollment>(entity =>
        {
            entity.HasIndex(x => new { x.CourseSelectionOfferingId, x.StudentId })
                .IsUnique();
            entity.HasIndex(x => new { x.StudentId, x.Status });
            entity.HasIndex(x => new
            {
                x.CourseSelectionOfferingId,
                x.Status,
                x.WaitlistedAt
            }).HasDatabaseName("IX_CE_Offering_Status_WaitlistedAt");
            entity.HasOne(x => x.CourseSelectionOffering)
                .WithMany(x => x.Enrollments)
                .HasForeignKey(x => x.CourseSelectionOfferingId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student)
                .WithMany()
                .HasForeignKey(x => x.StudentId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<GradeSheet>(entity =>
        {
            entity.Property(x => x.RegularWeight).HasPrecision(5, 1);
            entity.Property(x => x.FinalWeight).HasPrecision(5, 1);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => x.TeachingTaskId).IsUnique();
            entity.HasIndex(x => x.Status);
            entity.HasOne(x => x.TeachingTask)
                .WithMany()
                .HasForeignKey(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<GradeItem>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(60);
            entity.Property(x => x.Weight).HasPrecision(5, 1);
            entity.Property(x => x.SourceType)
                .HasDefaultValue(GradeItemSourceType.Manual)
                .HasSentinel((GradeItemSourceType)0);
            entity.HasIndex(x => new { x.GradeSheetId, x.SortOrder });
            entity.HasOne(x => x.GradeSheet)
                .WithMany(x => x.Items)
                .HasForeignKey(x => x.GradeSheetId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<GradeRecord>(entity =>
        {
            entity.Property(x => x.RegularScore).HasPrecision(5, 1);
            entity.Property(x => x.FinalScore).HasPrecision(5, 1);
            entity.Property(x => x.TotalScore).HasPrecision(5, 1);
            entity.Property(x => x.GradePoint).HasPrecision(3, 1);
            entity.Property(x => x.Notes).HasMaxLength(300);
            entity.HasIndex(x => new { x.GradeSheetId, x.StudentId }).IsUnique();
            entity.HasIndex(x => new { x.StudentId, x.TotalScore });
            entity.HasOne(x => x.GradeSheet)
                .WithMany(x => x.Records)
                .HasForeignKey(x => x.GradeSheetId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student)
                .WithMany()
                .HasForeignKey(x => x.StudentId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<GradeItemScore>(entity =>
        {
            entity.HasKey(x => new { x.GradeRecordId, x.GradeItemId });
            entity.Property(x => x.Score).HasPrecision(5, 1);
            entity.HasOne(x => x.GradeRecord)
                .WithMany(x => x.ItemScores)
                .HasForeignKey(x => x.GradeRecordId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.GradeItem)
                .WithMany(x => x.Scores)
                .HasForeignKey(x => x.GradeItemId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CourseGradeStatistic>(entity =>
        {
            entity.Property(x => x.HighestScore).HasPrecision(5, 1);
            entity.Property(x => x.AverageScore).HasPrecision(5, 1);
            entity.Property(x => x.LowestScore).HasPrecision(5, 1);
            entity.Property(x => x.PassRate).HasPrecision(5, 2);
            entity.HasIndex(x => new
            {
                x.CourseId, x.AcademicTermId, x.Scope, x.ScopeEntityId
            }).IsUnique().HasDatabaseName("UX_CourseGradeStatistics_Scope");
            entity.HasIndex(x => new { x.AcademicTermId, x.Scope, x.ScopeEntityId });
            entity.HasOne<Course>().WithMany().HasForeignKey(x => x.CourseId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne<AcademicTerm>().WithMany().HasForeignKey(x => x.AcademicTermId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<TeachingTaskGradeStatistic>(entity =>
        {
            entity.Property(x => x.HighestScore).HasPrecision(5, 1);
            entity.Property(x => x.AverageScore).HasPrecision(5, 1);
            entity.Property(x => x.MedianScore).HasPrecision(5, 1);
            entity.Property(x => x.LowestScore).HasPrecision(5, 1);
            entity.Property(x => x.StandardDeviation).HasPrecision(6, 2);
            entity.Property(x => x.PassRate).HasPrecision(5, 2);
            entity.Property(x => x.ExcellentRate).HasPrecision(5, 2);
            entity.HasIndex(x => x.GradeSheetId).IsUnique();
            entity.HasIndex(x => x.TeachingTaskId).IsUnique();
            entity.HasIndex(x => new { x.CourseId, x.AcademicTermId });
            entity.HasOne(x => x.GradeSheet).WithOne()
                .HasForeignKey<TeachingTaskGradeStatistic>(x => x.GradeSheetId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.TeachingTask).WithOne()
                .HasForeignKey<TeachingTaskGradeStatistic>(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne<Course>().WithMany().HasForeignKey(x => x.CourseId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne<AcademicTerm>().WithMany().HasForeignKey(x => x.AcademicTermId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<TeachingTaskGradeScoreBand>(entity =>
        {
            entity.Property(x => x.Label).HasMaxLength(30);
            entity.Property(x => x.LowerBound).HasPrecision(5, 1);
            entity.Property(x => x.UpperBound).HasPrecision(5, 1);
            entity.HasIndex(x => new
            {
                x.TeachingTaskGradeStatisticId,
                x.SortOrder
            }).IsUnique();
            entity.HasOne(x => x.TeachingTaskGradeStatistic)
                .WithMany(x => x.ScoreBands)
                .HasForeignKey(x => x.TeachingTaskGradeStatisticId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<CourseGradeStatisticsRefreshJob>(entity =>
        {
            entity.Property(x => x.ErrorMessage).HasMaxLength(2000);
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasIndex(x => x.GradeSheetId);
            entity.HasOne<GradeSheet>().WithMany().HasForeignKey(x => x.GradeSheetId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<AttendanceSheet>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.CheckInToken).HasMaxLength(64);
            entity.Property(x => x.TargetLatitude).HasPrecision(10, 7);
            entity.Property(x => x.TargetLongitude).HasPrecision(10, 7);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.TeachingTaskId, x.AttendanceDate });
            entity.HasIndex(x => x.CheckInToken).IsUnique();
            entity.HasOne(x => x.TeachingTask)
                .WithMany()
                .HasForeignKey(x => x.TeachingTaskId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<AttendanceRecord>(entity =>
        {
            entity.HasKey(x => new { x.AttendanceSheetId, x.StudentId });
            entity.Property(x => x.Notes).HasMaxLength(300);
            entity.Property(x => x.AppealReason).HasMaxLength(500);
            entity.Property(x => x.AppealReviewComment).HasMaxLength(300);
            entity.Property(x => x.CheckInLatitude).HasPrecision(10, 7);
            entity.Property(x => x.CheckInLongitude).HasPrecision(10, 7);
            entity.HasIndex(x => x.AppealStatus);
            entity.HasOne(x => x.AttendanceSheet)
                .WithMany(x => x.Records)
                .HasForeignKey(x => x.AttendanceSheetId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student)
                .WithMany()
                .HasForeignKey(x => x.StudentId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<AttendanceCheckInAttempt>(entity =>
        {
            entity.Property(x => x.FailureCode).HasMaxLength(64);
            entity.Property(x => x.DeviceIdentifierHash).HasMaxLength(64);
            entity.Property(x => x.DevicePlatform).HasMaxLength(32);
            entity.Property(x => x.IpAddress).HasMaxLength(64);
            entity.Property(x => x.UserAgent).HasMaxLength(500);
            entity.Property(x => x.RiskFlags).HasMaxLength(300);
            entity.Property(x => x.Latitude).HasPrecision(10, 7);
            entity.Property(x => x.Longitude).HasPrecision(10, 7);
            entity.HasIndex(x => new { x.AttendanceSheetId, x.StudentId, x.CreatedAt });
            entity.HasIndex(x => new { x.DeviceIdentifierHash, x.CreatedAt });
            entity.HasIndex(x => new { x.IpAddress, x.CreatedAt });
            entity.HasOne(x => x.AttendanceSheet)
                .WithMany(x => x.CheckInAttempts)
                .HasForeignKey(x => x.AttendanceSheetId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student)
                .WithMany()
                .HasForeignKey(x => x.StudentId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<ExamPlan>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.AcademicTermId, x.Status });
            entity.HasOne(x => x.AcademicTerm).WithMany()
                .HasForeignKey(x => x.AcademicTermId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<ExamSession>(entity =>
        {
            // Exam slot times are China-local wall-clock times, not instants.
            // Keep their existing API representation offset-free.
            entity.Property(x => x.StartsAt).HasConversion<UnspecifiedDateTimeConverter>();
            entity.Property(x => x.EndsAt).HasConversion<UnspecifiedDateTimeConverter>();
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.ExamPlanId, x.StartsAt });
            entity.HasIndex(x => x.TeachingTaskId);
            entity.HasIndex(x => new { x.ExamPlanId, x.ExamDate });
            entity.HasIndex(x => x.RequiredBuildingId);
            entity.Property(x => x.RequiredBuildingIds).HasColumnType("longtext");
            entity.HasOne(x => x.ExamPlan).WithMany(x => x.Sessions)
                .HasForeignKey(x => x.ExamPlanId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.TeachingTask).WithMany()
                .HasForeignKey(x => x.TeachingTaskId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Classroom).WithMany()
                .HasForeignKey(x => x.ClassroomId).OnDelete(DeleteBehavior.SetNull);
            entity.HasOne(x => x.RequiredBuilding).WithMany()
                .HasForeignKey(x => x.RequiredBuildingId).OnDelete(DeleteBehavior.SetNull);
        });
        builder.Entity<ExamSessionInvigilator>(entity =>
        {
            entity.HasKey(x => new { x.ExamSessionId, x.TeacherId });
            entity.HasOne(x => x.ExamSession).WithMany(x => x.Invigilators)
                .HasForeignKey(x => x.ExamSessionId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Teacher).WithMany()
                .HasForeignKey(x => x.TeacherId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<ExamRoomAssignment>(entity =>
        {
            entity.ToTable("ExamRooms");
            entity.Property(x => x.StartsAt).HasConversion<UnspecifiedDateTimeConverter>();
            entity.Property(x => x.EndsAt).HasConversion<UnspecifiedDateTimeConverter>();
            entity.HasIndex(x => new { x.ExamPlanId, x.StartsAt })
                .HasDatabaseName("IX_ExamRooms_Plan_Time");
            entity.HasIndex(x => new
                {
                    x.ExamPlanId,
                    x.ClassroomId,
                    x.StartsAt
                })
                .HasDatabaseName("IX_ExamRooms_Plan_Room_Time");
            entity.HasIndex(x => x.CourseId)
                .HasDatabaseName("IX_ExamRooms_CourseId");
            entity.HasOne(x => x.ExamPlan).WithMany(x => x.Rooms)
                .HasForeignKey(x => x.ExamPlanId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Course).WithMany()
                .HasForeignKey(x => x.CourseId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Classroom).WithMany()
                .HasForeignKey(x => x.ClassroomId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<ExamRoomSession>(entity =>
        {
            entity.ToTable("ExamRoomSessions");
            entity.HasKey(x => new { x.ExamRoomId, x.ExamSessionId });
            entity.HasIndex(x => x.ExamSessionId)
                .HasDatabaseName("IX_ExamRoomSessions_SessionId");
            entity.HasOne(x => x.ExamRoom).WithMany(x => x.SessionLinks)
                .HasForeignKey(x => x.ExamRoomId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.ExamSession).WithMany(x => x.RoomLinks)
                .HasForeignKey(x => x.ExamSessionId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<ExamSeatAssignment>(entity =>
        {
            entity.ToTable("ExamSeats");
            entity.HasKey(x => new { x.ExamRoomId, x.StudentId });
            entity.HasIndex(x => new { x.ExamSessionId, x.StudentId })
                .IsUnique()
                .HasDatabaseName("UX_ExamSeats_Session_Student");
            entity.HasIndex(x => x.StudentId)
                .HasDatabaseName("IX_ExamSeats_StudentId");
            entity.HasOne(x => x.ExamRoom).WithMany(x => x.Seats)
                .HasForeignKey(x => x.ExamRoomId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.ExamSession).WithMany(x => x.SeatAssignments)
                .HasForeignKey(x => x.ExamSessionId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<ExamRoomInvigilator>(entity =>
        {
            entity.ToTable("ExamRoomInvigilators");
            entity.HasKey(x => new { x.ExamRoomId, x.TeacherId });
            entity.HasIndex(x => x.TeacherId)
                .HasDatabaseName("IX_ExamRoomInvigilators_TeacherId");
            entity.HasOne(x => x.ExamRoom).WithMany(x => x.Invigilators)
                .HasForeignKey(x => x.ExamRoomId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Teacher).WithMany()
                .HasForeignKey(x => x.TeacherId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<ExamArrangementJob>(entity =>
        {
            entity.Property(x => x.CurrentStep).HasMaxLength(200);
            entity.Property(x => x.ResultMessage).HasMaxLength(2000);
            entity.Property(x => x.ErrorMessage).HasMaxLength(2000);
            entity.HasIndex(x => new { x.Kind, x.ActivePlanId })
                .IsUnique()
                .HasDatabaseName("UX_ExamArrangementJobs_Kind_ActivePlan");
            entity.HasIndex(x => new { x.Kind, x.PlanId, x.CreatedAt })
                .HasDatabaseName("IX_ExamArrangementJobs_Kind_Plan_CreatedAt");
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasIndex(x => x.RequestedByUserId);
        });
        builder.Entity<ExamSignInExportJob>(entity =>
        {
            entity.Property(x => x.CurrentStep).HasMaxLength(200);
            entity.Property(x => x.FileName).HasMaxLength(200);
            entity.Property(x => x.ErrorMessage).HasMaxLength(2000);
            entity.HasIndex(x => new { x.PlanId, x.CreatedAt });
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasIndex(x => x.RequestedByUserId);
        });
        builder.Entity<MakeupExamPlan>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.AcademicTermId, x.Status });
            entity.HasOne(x => x.AcademicTerm).WithMany()
                .HasForeignKey(x => x.AcademicTermId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<MakeupExamSession>(entity =>
        {
            // Makeup-exam slot times follow the same wall-clock convention.
            entity.Property(x => x.StartsAt).HasConversion<UnspecifiedDateTimeConverter>();
            entity.Property(x => x.EndsAt).HasConversion<UnspecifiedDateTimeConverter>();
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.MakeupExamPlanId, x.StartsAt });
            entity.HasIndex(x => x.TeachingTaskId);
            entity.HasIndex(x => new { x.MakeupExamPlanId, x.ExamDate });
            entity.HasIndex(x => x.RequiredBuildingId);
            entity.Property(x => x.RequiredBuildingIds).HasColumnType("longtext");
            entity.HasOne(x => x.MakeupExamPlan).WithMany(x => x.Sessions)
                .HasForeignKey(x => x.MakeupExamPlanId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.TeachingTask).WithMany()
                .HasForeignKey(x => x.TeachingTaskId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Classroom).WithMany()
                .HasForeignKey(x => x.ClassroomId).OnDelete(DeleteBehavior.SetNull);
            entity.HasOne(x => x.RequiredBuilding).WithMany()
                .HasForeignKey(x => x.RequiredBuildingId).OnDelete(DeleteBehavior.SetNull);
        });
        builder.Entity<MakeupExamSessionInvigilator>(entity =>
        {
            entity.HasKey(x => new { x.MakeupExamSessionId, x.TeacherId });
            entity.HasOne(x => x.MakeupExamSession).WithMany(x => x.Invigilators)
                .HasForeignKey(x => x.MakeupExamSessionId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Teacher).WithMany()
                .HasForeignKey(x => x.TeacherId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<MakeupExamEnrollment>(entity =>
        {
            entity.HasKey(x => new { x.MakeupExamSessionId, x.StudentId });
            entity.HasIndex(x => new { x.StudentId, x.MakeupExamSessionId });
            entity.Property(x => x.MakeupScore).HasPrecision(5, 1);
            entity.HasOne(x => x.MakeupExamSession).WithMany(x => x.Enrollments)
                .HasForeignKey(x => x.MakeupExamSessionId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.SourceGradeRecord).WithMany()
                .HasForeignKey(x => x.SourceGradeRecordId).OnDelete(DeleteBehavior.SetNull);
            entity.HasOne(x => x.SourceDeferredExam).WithMany()
                .HasForeignKey(x => x.SourceDeferredExamId).OnDelete(DeleteBehavior.SetNull);
        });
        builder.Entity<MakeupExamAutoJob>(entity =>
        {
            entity.Property(x => x.ErrorMessage).HasMaxLength(2000);
            entity.HasIndex(x => new { x.MakeupExamPlanId, x.CreatedAt });
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasOne(x => x.MakeupExamPlan).WithMany()
                .HasForeignKey(x => x.MakeupExamPlanId).OnDelete(DeleteBehavior.Cascade);
        });
        builder.Entity<StudentStatusChange>(entity =>
        {
            entity.Property(x => x.Reason).HasMaxLength(1000);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new { x.StudentId, x.State });
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<GraduationAuditBatch>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.GraduationYear, x.EnrollmentYear });
            entity.HasIndex(x => x.Status);
        });
        builder.Entity<GraduationAuditResult>(entity =>
        {
            entity.Property(x => x.RequiredCredits).HasPrecision(6, 2);
            entity.Property(x => x.EarnedCredits).HasPrecision(6, 2);
            entity.Property(x => x.MissingCourseNames).HasMaxLength(2000);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new { x.GraduationAuditBatchId, x.StudentId })
                .IsUnique();
            entity.HasIndex(x => new { x.Conclusion, x.IsOverridden });
            entity.HasOne(x => x.GraduationAuditBatch).WithMany(x => x.Results)
                .HasForeignKey(x => x.GraduationAuditBatchId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.CurriculumPlan).WithMany()
                .HasForeignKey(x => x.CurriculumPlanId).OnDelete(DeleteBehavior.SetNull);
        });
        builder.Entity<DegreeAwardBatch>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.DegreeName).HasMaxLength(80);
            entity.Property(x => x.MinimumGradePoint).HasPrecision(3, 2);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.GraduationYear, x.Status });
        });
        builder.Entity<DegreeAwardResult>(entity =>
        {
            entity.Property(x => x.AverageGradePoint).HasPrecision(4, 2);
            entity.Property(x => x.ExceptionReason).HasMaxLength(500);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new { x.DegreeAwardBatchId, x.StudentId }).IsUnique();
            entity.HasIndex(x => new { x.Conclusion, x.IsOverridden });
            entity.HasOne(x => x.DegreeAwardBatch).WithMany(x => x.Results)
                .HasForeignKey(x => x.DegreeAwardBatchId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.GraduationAuditResult).WithMany()
                .HasForeignKey(x => x.GraduationAuditResultId)
                .OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<GraduationClearanceBatch>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.GraduationYear, x.Status });
        });
        builder.Entity<GraduationClearanceItem>(entity =>
        {
            entity.Property(x => x.Code).HasMaxLength(30);
            entity.Property(x => x.Name).HasMaxLength(100);
            entity.Property(x => x.ResponsibleUnit).HasMaxLength(100);
            entity.Property(x => x.ResponsibleRole).HasMaxLength(30);
            entity.HasIndex(x => new { x.GraduationClearanceBatchId, x.Code }).IsUnique();
            entity.HasOne(x => x.GraduationClearanceBatch).WithMany(x => x.Items)
                .HasForeignKey(x => x.GraduationClearanceBatchId)
                .OnDelete(DeleteBehavior.Cascade);
        });
        builder.Entity<GraduationClearanceRecord>(entity =>
        {
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.GraduationClearanceItemId, x.StudentId })
                .IsUnique();
            entity.HasIndex(x => new { x.StudentId, x.Status });
            entity.HasOne(x => x.GraduationClearanceItem).WithMany(x => x.Records)
                .HasForeignKey(x => x.GraduationClearanceItemId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CourseExemption>(entity =>
        {
            entity.Property(x => x.Reason).HasMaxLength(500);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasIndex(x => new { x.StudentId, x.TeachingTaskId }).IsUnique();
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.TeachingTask).WithMany()
                .HasForeignKey(x => x.TeachingTaskId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<DeferredExam>(entity =>
        {
            entity.Property(x => x.Reason).HasMaxLength(500);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasIndex(x => new { x.StudentId, x.TeachingTaskId }).IsUnique();
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.TeachingTask).WithMany()
                .HasForeignKey(x => x.TeachingTaskId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<GradeModification>(entity =>
        {
            entity.Property(x => x.CurrentScore).HasPrecision(5, 1);
            entity.Property(x => x.RequestedScore).HasPrecision(5, 1);
            entity.Property(x => x.Reason).HasMaxLength(500);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasOne(x => x.GradeRecord).WithMany()
                .HasForeignKey(x => x.GradeRecordId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<OtherExamBatch>(entity =>
        {
            entity.Property(x => x.ExamCode).HasMaxLength(60);
            entity.Property(x => x.Name).HasMaxLength(150);
            entity.Property(x => x.Organizer).HasMaxLength(150);
            entity.Property(x => x.LevelOptions).HasMaxLength(500);
            entity.Property(x => x.MaxScore).HasPrecision(8, 2);
            entity.HasIndex(x => new { x.Status, x.ExamDate });
        });
        builder.Entity<OtherExamResult>(entity =>
        {
            entity.Property(x => x.Score).HasPrecision(8, 2);
            entity.Property(x => x.Level).HasMaxLength(50);
            entity.Property(x => x.Notes).HasMaxLength(500);
            entity.HasIndex(x => new { x.OtherExamBatchId, x.StudentId, x.AttemptNumber }).IsUnique();
            entity.HasIndex(x => new { x.StudentId, x.OtherExamBatchId });
            entity.HasOne(x => x.OtherExamBatch).WithMany(x => x.Results)
                .HasForeignKey(x => x.OtherExamBatchId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
        });
        builder.Entity<WarningRule>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(100);
            entity.Property(x => x.Threshold).HasPrecision(7, 2);
            entity.Property(x => x.Description).HasMaxLength(300);
            entity.HasIndex(x => new { x.AcademicTermId, x.Type }).IsUnique();
            entity.HasOne(x => x.AcademicTerm).WithMany()
                .HasForeignKey(x => x.AcademicTermId).OnDelete(DeleteBehavior.Cascade);
        });
        builder.Entity<WarningRecord>(entity =>
        {
            entity.Property(x => x.TriggerValue).HasPrecision(7, 2);
            entity.Property(x => x.Detail).HasMaxLength(1000);
            entity.Property(x => x.AcknowledgeComment).HasMaxLength(300);
            entity.HasIndex(x => new { x.StudentId, x.AcademicTermId, x.Type }).IsUnique();
            entity.HasIndex(x => x.Status);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
        });

        // ── Evaluation ──
        builder.Entity<EvaluationSetup>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(120);
            entity.HasIndex(x => new { x.AcademicTermId, x.Status });
            entity.HasOne(x => x.AcademicTerm).WithMany()
                .HasForeignKey(x => x.AcademicTermId).OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<EvaluationDimension>(entity =>
        {
            entity.Property(x => x.Name).HasMaxLength(60);
            entity.HasIndex(x => new { x.EvaluationSetupId, x.SortOrder });
            entity.HasOne(x => x.EvaluationSetup).WithMany(x => x.Dimensions)
                .HasForeignKey(x => x.EvaluationSetupId).OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<EvaluationRecord>(entity =>
        {
            entity.HasIndex(x => new { x.EvaluationSetupId, x.StudentId, x.TeachingTaskId }).IsUnique();
            entity.HasOne(x => x.EvaluationSetup).WithMany(x => x.Records)
                .HasForeignKey(x => x.EvaluationSetupId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.TeachingTask).WithMany()
                .HasForeignKey(x => x.TeachingTaskId).OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<EvaluationScore>(entity =>
        {
            entity.HasKey(x => new { x.EvaluationRecordId, x.EvaluationDimensionId });
            entity.HasOne(x => x.EvaluationRecord).WithMany(x => x.Scores)
                .HasForeignKey(x => x.EvaluationRecordId).OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.EvaluationDimension).WithMany(x => x.Scores)
                .HasForeignKey(x => x.EvaluationDimensionId).OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CourseSubstitution>(entity =>
        {
            entity.Property(x => x.Reason).HasMaxLength(500);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasIndex(x => new { x.StudentId, x.OriginalCourseId }).IsUnique();
            entity.HasOne(x => x.Student).WithMany()
                .HasForeignKey(x => x.StudentId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.OriginalCourse).WithMany()
                .HasForeignKey(x => x.OriginalCourseId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.SubstituteCourse).WithMany()
                .HasForeignKey(x => x.SubstituteCourseId).OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<CourseAdjustment>(entity =>
        {
            entity.Property(x => x.Reason).HasMaxLength(500);
            entity.Property(x => x.ReviewComment).HasMaxLength(500);
            entity.HasIndex(x => new { x.TeachingTaskId, x.Status });
            entity.HasIndex(x => x.ApplicantUserId);
            entity.HasIndex(x => new { x.Status, x.CreatedAt });
            entity.HasIndex(x => new { x.SourceScheduleEntryId, x.SourceWeek });
            entity.HasOne(x => x.TeachingTask).WithMany()
                .HasForeignKey(x => x.TeachingTaskId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.Classroom).WithMany()
                .HasForeignKey(x => x.ClassroomId).OnDelete(DeleteBehavior.SetNull);
            entity.HasOne(x => x.SubstituteTeacher).WithMany()
                .HasForeignKey(x => x.SubstituteTeacherId).OnDelete(DeleteBehavior.SetNull);
        });

        builder.Entity<Notification>(entity =>
        {
            entity.Property(x => x.Title).HasMaxLength(200);
            entity.Property(x => x.Content).HasColumnType("longtext");
            entity.Property(x => x.LinkUrl).HasMaxLength(300);
            // Each inbox query starts with its recipient.  Keep the selected
            // sort fields in the index so large inboxes do not need a filesort.
            entity.HasIndex(x => new { x.UserId, x.CreatedAt, x.Id });
            entity.HasIndex(x => new { x.UserId, x.IsRead, x.CreatedAt, x.Id });
            entity.HasIndex(x => new { x.UserId, x.Category, x.CreatedAt, x.Id });
            entity.HasIndex(x => x.MessageDispatchId);
            entity.HasIndex(x => x.CreatedAt);
            entity.HasOne(x => x.MessageDispatch)
                .WithMany(x => x.Notifications)
                .HasForeignKey(x => x.MessageDispatchId)
                .OnDelete(DeleteBehavior.Cascade);
        });

        builder.Entity<MessageDispatch>(entity =>
        {
            entity.Property(x => x.SenderName).HasMaxLength(100);
            entity.Property(x => x.Title).HasMaxLength(200);
            entity.Property(x => x.Content).HasColumnType("longtext");
            entity.Property(x => x.AudienceName).HasMaxLength(200);
            entity.Property(x => x.LinkUrl).HasMaxLength(300);
            entity.HasIndex(x => new { x.SenderUserId, x.CreatedAt });
        });

        builder.Entity<AuditLog>(entity =>
        {
            entity.Property(x => x.Method).HasMaxLength(10);
            entity.Property(x => x.Path).HasMaxLength(300);
            entity.Property(x => x.UserName).HasMaxLength(100);
            entity.Property(x => x.IpAddress).HasMaxLength(64);
            entity.HasIndex(x => x.CreatedAt);
        });

        builder.Entity<BackgroundJobOutboxMessage>(entity =>
        {
            entity.Property(x => x.LastError).HasMaxLength(2000);
            entity.HasIndex(x => new { x.JobKind, x.JobId }).IsUnique();
            entity.HasIndex(x => new { x.State, x.CreatedAt });
            entity.HasIndex(x => new { x.State, x.CompletedAt });
            entity.HasIndex(x => x.LeaseExpiresAt);
        });

        builder.Entity<AppUpdateRelease>(entity =>
        {
            entity.Property(x => x.Platform)
                .HasConversion<string>()
                .HasMaxLength(20);
            entity.Property(x => x.Channel)
                .HasConversion<string>()
                .HasMaxLength(20);
            entity.Property(x => x.Status)
                .HasConversion<string>()
                .HasMaxLength(20);
            entity.Property(x => x.Version).HasMaxLength(40);
            entity.Property(x => x.NativeVersion).HasMaxLength(40);
            entity.Property(x => x.ReleaseNotes).HasMaxLength(1000);
            entity.Property(x => x.FileName).HasMaxLength(180);
            entity.Property(x => x.Sha256).HasMaxLength(64);
            entity.Property(x => x.BundleContent).HasColumnType("longblob");
            entity.Property(x => x.CreatedByUserName).HasMaxLength(100);
            entity.Property(x => x.PublishedByUserName).HasMaxLength(100);
            entity.HasIndex(x => new
            {
                x.Platform,
                x.Channel,
                x.NativeVersion,
                x.Version
            }).IsUnique();
            entity.HasIndex(x => new
            {
                x.Platform,
                x.Channel,
                x.NativeVersion,
                x.Status
            });
            entity.HasIndex(x => x.CreatedAt);
        });

        builder.Entity<SystemFeatureSetting>(entity =>
        {
            entity.Property(x => x.Key).HasMaxLength(100);
            entity.HasIndex(x => x.Key).IsUnique();
        });

        builder.Entity<CourseGradeStatisticsRefreshSetting>(entity =>
        {
            entity.Property(x => x.Key).HasMaxLength(50);
            entity.HasIndex(x => x.Key).IsUnique();
        });

        builder.Entity<OfficialDocument>(entity =>
        {
            entity.Property(x => x.DocumentNumber).HasMaxLength(50);
            entity.Property(x => x.VerificationCodeHash).HasMaxLength(64);
            entity.Property(x => x.Purpose).HasMaxLength(200);
            entity.Property(x => x.SnapshotJson).HasColumnType("longtext");
            entity.Property(x => x.PdfContent).HasColumnType("longblob");
            entity.Property(x => x.PdfSha256).HasMaxLength(64);
            entity.Property(x => x.InvalidationReason).HasMaxLength(500);
            entity.HasIndex(x => x.DocumentNumber).IsUnique();
            entity.HasIndex(x => x.VerificationCodeHash).IsUnique();
            entity.HasIndex(x => new { x.StudentId, x.IssuedAt });
            entity.HasIndex(x => new { x.Status, x.IssuedAt });
            entity.HasOne(x => x.Student)
                .WithMany()
                .HasForeignKey(x => x.StudentId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.IssuedByUser)
                .WithMany()
                .HasForeignKey(x => x.IssuedByUserId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(x => x.InvalidatedByUser)
                .WithMany()
                .HasForeignKey(x => x.InvalidatedByUserId)
                .OnDelete(DeleteBehavior.Restrict);
            entity.HasIndex(x => x.ReissuedFromDocumentId).IsUnique();
            entity.HasOne(x => x.ReissuedFromDocument)
                .WithMany()
                .HasForeignKey(x => x.ReissuedFromDocumentId)
                .OnDelete(DeleteBehavior.Restrict);
        });

        builder.Entity<OfficialDocumentDownload>(entity =>
        {
            entity.Property(x => x.IpAddress).HasMaxLength(64);
            entity.Property(x => x.UserAgent).HasMaxLength(500);
            entity.HasIndex(x => new { x.OfficialDocumentId, x.CreatedAt });
            entity.HasIndex(x => new { x.DownloadedByUserId, x.CreatedAt });
            entity.HasOne(x => x.OfficialDocument)
                .WithMany(x => x.Downloads)
                .HasForeignKey(x => x.OfficialDocumentId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasOne(x => x.DownloadedByUser)
                .WithMany()
                .HasForeignKey(x => x.DownloadedByUserId)
                .OnDelete(DeleteBehavior.Restrict);
        });
    }

    public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        foreach (var entry in ChangeTracker.Entries<EntityBase>()
                     .Where(x => x.State == EntityState.Modified))
        {
            entry.Entity.UpdatedAt = DateTime.UtcNow;
        }

        return base.SaveChangesAsync(cancellationToken);
    }

    private static void ConfigureCatalog<TEntity>(ModelBuilder builder)
        where TEntity : CatalogEntity
    {
        builder.Entity<TEntity>(entity =>
        {
            entity.Property(x => x.Code).HasMaxLength(40);
            entity.Property(x => x.Name).HasMaxLength(100);
            entity.HasIndex(x => x.Code).IsUnique();
            entity.HasIndex(x => new { x.IsEnabled, x.SortOrder });
        });
    }
}

public sealed class DateOnlyDateTimeConverter()
    : ValueConverter<DateOnly, DateTime>(
        date => date.ToDateTime(TimeOnly.MinValue),
        value => DateOnly.FromDateTime(value));

public sealed class TimeOnlyTimeSpanConverter()
    : ValueConverter<TimeOnly, TimeSpan>(
        time => time.ToTimeSpan(),
        value => TimeOnly.FromTimeSpan(value));

public sealed class UtcDateTimeConverter()
    : ValueConverter<DateTime, DateTime>(
        value => value.Kind == DateTimeKind.Local
            ? value.ToUniversalTime()
            : DateTime.SpecifyKind(value, DateTimeKind.Utc),
        value => DateTime.SpecifyKind(value, DateTimeKind.Utc));

public sealed class UnspecifiedDateTimeConverter()
    : ValueConverter<DateTime, DateTime>(
        value => DateTime.SpecifyKind(value, DateTimeKind.Unspecified),
        value => DateTime.SpecifyKind(value, DateTimeKind.Unspecified));
