using Microsoft.EntityFrameworkCore;

namespace Jiaowu.Api.Infrastructure.Persistence;

public sealed class DevelopmentSqliteMigrator(
    AppDbContext db,
    ILogger<DevelopmentSqliteMigrator> logger)
{
    private const string PeopleAndCoursesMigration = "20260724_01_people_courses";
    private const string CurriculumPlansMigration = "20260724_02_curriculum_plans";
    private const string TeachingTasksMigration = "20260724_03_teaching_tasks";
    private const string SchedulesMigration = "20260724_04_schedules";
    private const string ClassCounselorMigration = "20260724_05_class_counselor";
    private const string CourseSelectionMigration = "20260724_06_course_selection";
    private const string GradesMigration = "20260724_07_grades";
    private const string ExamsMigration = "20260724_08_exams";
    private const string AttendanceMigration = "20260724_08b_attendance";
    private const string StudentStatusChangesMigration = "20260724_09_student_status_changes";
    private const string GraduationAuditsMigration = "20260724_10_graduation_audits";
    private const string DegreeAwardsMigration = "20260724_11_degree_awards";
    private const string GraduationClearanceMigration = "20260724_12_graduation_clearance";
    private const string CourseCategoriesMigration = "20260724_13_course_categories";
    private const string SchedulingOptimizationMigration =
        "20260724_14_scheduling_optimization";
    private const string TeacherCourseApplicationsMigration =
        "20260724_15_teacher_course_applications";
     private const string AutomaticScheduleJobsMigration =
         "20260724_16_automatic_schedule_jobs";
    private const string TeachingTaskSchedulingModesMigration =
        "20260725_17_teaching_task_scheduling_modes";
    private const string SchedulePublishJobsMigration =
        "20260725_18_schedule_publish_jobs";
    private const string FlexibleGradesMigration =
        "20260725_19_flexible_grades";
    private const string ExamSchedulingOptimizationMigration =
        "20260725_20_exam_scheduling_optimization";
    private const string RetakeEnrollmentMigration =
        "20260725_21_retake_enrollment";
    private const string CourseAdjustmentsMigration =
        "20260725_22_course_adjustments";
    private const string AttendanceAppealMigration =
        "20260725_23_attendance_appeal";
    private const string AttendanceCheckInMigration =
        "20260726_26_attendance_check_in";
    private const string ApprovalTablesMigration =
        "20260725_24_approval_tables";
    private const string AcademicWarningsMigration =
        "20260725_25_academic_warnings";
    private const string AcademicTermArchivingMigration =
        "20260726_27_academic_term_archiving";
    private const string CourseSelectionWaitlistMigration =
        "20260726_28_course_selection_waitlist";
    private const string PersonalCalendarSubscriptionMigration =
        "20260726_29_personal_calendar_subscription";
    private const string OfficialDocumentsMigration =
        "20260726_30_official_documents";
    private const string UnifiedMessageCenterMigration =
        "20260726_31_unified_message_center";
    private const string ClassroomReservationsMigration =
        "20260726_32_classroom_reservations";
    private const string BackgroundJobOutboxMigration =
        "20260726_33_background_job_outbox";
    private const string CourseAdjustmentOccurrencesMigration =
        "20260727_34_course_adjustment_occurrences";
    private const string AcademicPlanningPrerequisitesMigration =
        "20260727_35_academic_planning_prerequisites";
    private const string ExamRoomMixingMigration =
        "20260727_36_exam_room_mixing";
    private const string AttendanceCheckInAuditMigration =
        "20260728_37_attendance_check_in_audit";
    private const string ExamPublishJobsMigration =
        "20260728_38_exam_publish_jobs";
    private const string ExperimentManagementMigration =
        "20260728_39_experiment_management";
    private const string ExperimentGradeManagementMigration =
        "20260728_40_experiment_grade_management";
    private const string AppUpdateReleasesMigration =
        "20260729_41_app_update_releases";
    private const string IntegratedExperimentSchedulingMigration =
        "20260802_42_integrated_experiment_scheduling";
    private const string RefreshSessionsMigration =
        "20260803_43_refresh_sessions";
    private const string StudentPersonalProfileMigration =
        "20260803_44_student_personal_profile";
    private const string OtherExamResultsMigration =
        "20260808_45_other_exam_results";
    private const string CourseGradeStatisticsMigration =
        "20260808_46_course_grade_statistics";
    private const string CourseGradeDistributionMigration =
        "20260809_47_course_grade_distribution";
    private const string TeachingTaskGradeAnalyticsMigration =
        "20260809_48_teaching_task_grade_analytics";
    private const string SwaggerDocumentationSettingMigration =
        "20260809_49_swagger_documentation_setting";
    private const string ExperimentClassroomConstraintsMigration =
        "20260809_50_experiment_classroom_constraints";
    private const string SeparateExperimentClassroomScopeMigration =
        "20260809_51_separate_experiment_classroom_scope";
    private const string ReusableCourseGroupsMigration =
        "20260809_52_reusable_course_groups";
    private const string CourseGradeStatisticsRefreshSettingsMigration =
        "20260809_53_course_grade_statistics_refresh_settings";
    private const string ExperimentCourseGradesMigration =
        "20260809_54_experiment_course_grades";
    private const string NotificationInboxIndexesMigration =
        "20260810_55_notification_inbox_indexes";
    private const string SelfScheduledExperimentSelectionMigration =
        "20260811_56_self_scheduled_experiment_selection";

    public async Task MigrateAsync(CancellationToken cancellationToken = default)
    {
        if (!db.Database.IsSqlite())
        {
            return;
        }

        await db.Database.ExecuteSqlRawAsync(
            """
            CREATE TABLE IF NOT EXISTS "__DevelopmentSchemaHistory" (
                "MigrationId" TEXT NOT NULL CONSTRAINT "PK___DevelopmentSchemaHistory" PRIMARY KEY,
                "AppliedAt" TEXT NOT NULL
            );
            """,
            cancellationToken);

        await ApplyMigrationAsync(
            PeopleAndCoursesMigration,
            PeopleAndCoursesStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            CurriculumPlansMigration,
            CurriculumPlansStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            TeachingTasksMigration,
            TeachingTasksStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            SchedulesMigration,
            SchedulesStatements,
            cancellationToken);
        var counselorColumnExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('AdministrativeClasses')
                WHERE name = 'CounselorUserId'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ClassCounselorMigration,
            counselorColumnExists
                ? ClassCounselorStatements.Skip(1)
                : ClassCounselorStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            CourseSelectionMigration,
            CourseSelectionStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            GradesMigration,
            GradesStatements,
            cancellationToken);
        await ApplyMigrationAsync(ExamsMigration, ExamsStatements, cancellationToken);
        await ApplyMigrationAsync(
            StudentStatusChangesMigration,
            StudentStatusChangesStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            GraduationAuditsMigration,
            GraduationAuditsStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            DegreeAwardsMigration,
            DegreeAwardsStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            GraduationClearanceMigration,
            GraduationClearanceStatements,
            cancellationToken);
        var courseCategoryColumnExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('Courses')
                WHERE name = 'CourseCategoryId'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            CourseCategoriesMigration,
            courseCategoryColumnExists
                ? CourseCategoriesStatements.Where(
                    statement => !statement.StartsWith(
                        "ALTER TABLE", StringComparison.OrdinalIgnoreCase))
                : CourseCategoriesStatements,
            cancellationToken);
        var schedulingOptimizationExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'ScheduleTimeSlots'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            SchedulingOptimizationMigration,
            schedulingOptimizationExists ? [] : SchedulingOptimizationStatements,
            cancellationToken);
        var teacherCourseApplicationsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'TeacherCourseApplications'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            TeacherCourseApplicationsMigration,
            teacherCourseApplicationsExist ? [] : TeacherCourseApplicationStatements,
            cancellationToken);
        var automaticScheduleJobsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'AutomaticScheduleJobs'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
         await ApplyMigrationAsync(
             AutomaticScheduleJobsMigration,
             automaticScheduleJobsExist ? [] : AutomaticScheduleJobStatements,
             cancellationToken);
        var teachingTaskSchedulingModeExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('TeachingTasks')
                WHERE name = 'SchedulingMode'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            TeachingTaskSchedulingModesMigration,
            teachingTaskSchedulingModeExists ? [] : TeachingTaskSchedulingModeStatements,
            cancellationToken);
        var schedulePublishJobsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'SchedulePublishJobs'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            SchedulePublishJobsMigration,
            schedulePublishJobsExist ? [] : SchedulePublishJobStatements,
            cancellationToken);

        var midtermWeightExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('GradeSheets')
                WHERE name = 'MidtermWeight'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            FlexibleGradesMigration,
            midtermWeightExists
                ? FlexibleGradesUpgradeStatements
                : FlexibleGradesNewStatements,
            cancellationToken);

        var attendanceSheetsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'AttendanceSheets'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            AttendanceMigration,
            attendanceSheetsExist ? [] : AttendanceStatements,
            cancellationToken);

        var examSchedulingOptimizationExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('ExamSessions')
                WHERE name = 'ExamDate'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ExamSchedulingOptimizationMigration,
            examSchedulingOptimizationExists
                ? []
                : ExamSchedulingOptimizationStatements,
            cancellationToken);

        var retakeEnrollmentExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('CourseEnrollments')
                WHERE name = 'EnrollmentType'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            RetakeEnrollmentMigration,
            retakeEnrollmentExists ? [] : RetakeEnrollmentStatements,
            cancellationToken);

        var courseAdjustmentsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'CourseAdjustments'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            CourseAdjustmentsMigration,
            courseAdjustmentsExist ? [] : CourseAdjustmentsStatements,
            cancellationToken);

        var courseAdjustmentOccurrencesExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('CourseAdjustments')
                WHERE name = 'SourceScheduleEntryId'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            CourseAdjustmentOccurrencesMigration,
            courseAdjustmentOccurrencesExist
                ? []
                : CourseAdjustmentOccurrencesStatements,
            cancellationToken);

        var attendanceAppealExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('AttendanceRecords')
                WHERE name = 'AppealStatus'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            AttendanceAppealMigration,
            attendanceAppealExists ? [] : AttendanceAppealStatements,
            cancellationToken);

        var attendanceCheckInExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('AttendanceSheets')
                WHERE name = 'CheckInMethod'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            AttendanceCheckInMigration,
            attendanceCheckInExists ? [] : AttendanceCheckInStatements,
            cancellationToken);
        var attendanceCheckInAttemptsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'AttendanceCheckInAttempts'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            AttendanceCheckInAuditMigration,
            attendanceCheckInAttemptsExist ? [] : AttendanceCheckInAuditStatements,
            cancellationToken);

        var approvalTablesExist = await db.Database
            .SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'CourseExemptions'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ApprovalTablesMigration,
            approvalTablesExist ? [] : ApprovalTableStatements,
            cancellationToken);

        var warningRulesExist = await db.Database
            .SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'WarningRules'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            AcademicWarningsMigration,
            warningRulesExist ? [] : AcademicWarningStatements,
            cancellationToken);

        var evaluationSetupsExist = await db.Database
            .SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'EvaluationSetups'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            TeachingEvaluationMigration,
            evaluationSetupsExist ? [] : TeachingEvaluationStatements,
            cancellationToken);

        var makeupExamsExist = await db.Database
            .SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'MakeupExamPlans'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            MakeupExamsMigration,
            makeupExamsExist ? [] : MakeupExamStatements,
            cancellationToken);

        var makeupAutoJobsExist = await db.Database
            .SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'MakeupExamAutoJobs'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            MakeupExamAutoJobsMigration,
            makeupAutoJobsExist ? [] : MakeupExamAutoJobStatements,
            cancellationToken);

        var examArrangementJobsExist = await db.Database
            .SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'ExamArrangementJobs'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ExamArrangementJobsMigration,
            examArrangementJobsExist ? [] : ExamArrangementJobStatements,
            cancellationToken);

        var exportJobsExist = await db.Database
            .SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'ExamSignInExportJobs'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ExamSignInExportJobsMigration,
            exportJobsExist ? [] : ExamSignInExportJobStatements,
            cancellationToken);

        var academicTermArchivingExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('AcademicTerms')
                WHERE name = 'IsArchived'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            AcademicTermArchivingMigration,
            academicTermArchivingExists ? [] : AcademicTermArchivingStatements,
            cancellationToken);

        var courseSelectionWaitlistExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('CourseEnrollments')
                WHERE name = 'WaitlistedAt'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            CourseSelectionWaitlistMigration,
            courseSelectionWaitlistExists ? [] : CourseSelectionWaitlistStatements,
            cancellationToken);

        var personalCalendarSubscriptionExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('AspNetUsers')
                WHERE name = 'CalendarSubscriptionStamp'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            PersonalCalendarSubscriptionMigration,
            personalCalendarSubscriptionExists
                ? []
                : PersonalCalendarSubscriptionStatements,
            cancellationToken);

        var officialDocumentsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'OfficialDocuments'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            OfficialDocumentsMigration,
            officialDocumentsExist ? [] : OfficialDocumentStatements,
            cancellationToken);

        var messageDispatchesExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'MessageDispatches'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            UnifiedMessageCenterMigration,
            messageDispatchesExist ? [] : UnifiedMessageCenterStatements,
            cancellationToken);

        var classroomReservationsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'ClassroomReservations'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ClassroomReservationsMigration,
            classroomReservationsExist ? [] : ClassroomReservationStatements,
            cancellationToken);

        var backgroundJobOutboxExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'BackgroundJobOutboxMessages'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            BackgroundJobOutboxMigration,
            backgroundJobOutboxExists ? [] : BackgroundJobOutboxStatements,
            cancellationToken);

        var coursePrerequisitesExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'CoursePrerequisites'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            AcademicPlanningPrerequisitesMigration,
            coursePrerequisitesExist ? [] : AcademicPlanningPrerequisiteStatements,
            cancellationToken);

        var examRoomsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'ExamRooms'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ExamRoomMixingMigration,
            examRoomsExist ? [] : ExamRoomMixingStatements,
            cancellationToken);

        var examPublishJobsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'ExamPublishJobs'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ExamPublishJobsMigration,
            examPublishJobsExist ? [] : ExamPublishJobStatements,
            cancellationToken);

        var experimentProjectsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'ExperimentProjects'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ExperimentManagementMigration,
            experimentProjectsExist ? [] : ExperimentManagementStatements,
            cancellationToken);

        var gradeItemSourceExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('GradeItems')
                WHERE name = 'SourceType'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        var experimentGradeSheetsExist = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'ExperimentGradeSheets'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ExperimentGradeManagementMigration,
            (gradeItemSourceExists
                    ? []
                    : ExperimentGradeItemSourceStatements)
                .Concat(experimentGradeSheetsExist
                    ? []
                    : ExperimentGradeManagementStatements),
            cancellationToken);
        await ApplyMigrationAsync(
            AppUpdateReleasesMigration,
            AppUpdateReleasesStatements,
            cancellationToken);
        var scheduleEntryKindExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('ScheduleEntries')
                WHERE name = 'Kind'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            IntegratedExperimentSchedulingMigration,
            scheduleEntryKindExists
                ? []
                : IntegratedExperimentSchedulingStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            RefreshSessionsMigration,
            RefreshSessionsStatements,
            cancellationToken);
        var studentPersonalProfileExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('Students')
                WHERE name = 'SpecialTags'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            StudentPersonalProfileMigration,
            studentPersonalProfileExists ? [] : StudentPersonalProfileStatements,
            cancellationToken);
        var otherExamCodeExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM pragma_table_info('OtherExamBatches')
                WHERE name = 'ExamCode'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        var otherExamBatchExists = await db.Database
            .SqlQueryRaw<int>(
                """
                SELECT COUNT(*) AS "Value"
                FROM sqlite_master
                WHERE type = 'table' AND name = 'OtherExamBatches'
                """)
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            OtherExamResultsMigration,
            !otherExamBatchExists
                ? OtherExamResultsStatements.Skip(1)
                : otherExamCodeExists
                    ? OtherExamResultsStatements.Skip(1)
                    : OtherExamResultsStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            CourseGradeStatisticsMigration,
            CourseGradeStatisticsStatements,
            cancellationToken);
        var courseGradeStatisticColumns = (await db.Database
            .SqlQueryRaw<string>(
                """
                SELECT name AS "Value"
                FROM pragma_table_info('CourseGradeStatistics')
                """)
            .ToListAsync(cancellationToken))
            .ToHashSet(StringComparer.OrdinalIgnoreCase);
        var missingDistributionStatements = CourseGradeDistributionColumns
            .Select((column, index) => new { column, index })
            .Where(x => !courseGradeStatisticColumns.Contains(x.column))
            .Select(x => CourseGradeDistributionStatements[x.index]);
        await ApplyMigrationAsync(
            CourseGradeDistributionMigration,
            missingDistributionStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            TeachingTaskGradeAnalyticsMigration,
            TeachingTaskGradeAnalyticsStatements,
            cancellationToken);
        var gradeRefreshSettingsExist = await db.Database
            .SqlQueryRaw<int>(
                "SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'CourseGradeStatisticsRefreshSettings'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            CourseGradeStatisticsRefreshSettingsMigration,
            gradeRefreshSettingsExist ? [] : CourseGradeStatisticsRefreshSettingsStatements,
            cancellationToken);
        var swaggerSettingsExist = await db.Database
            .SqlQueryRaw<int>(
                "SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'SystemFeatureSettings'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            SwaggerDocumentationSettingMigration,
            swaggerSettingsExist ? [] : SwaggerDocumentationSettingStatements,
            cancellationToken);
        var experimentClassroomConstraintsExist = await db.Database
            .SqlQueryRaw<int>(
                "SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'TeachingTaskAllowedExperimentClassrooms'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ExperimentClassroomConstraintsMigration,
            experimentClassroomConstraintsExist ? [] : ExperimentClassroomConstraintStatements,
            cancellationToken);
        var experimentScopeColumns = (await db.Database.SqlQueryRaw<string>(
                "SELECT name AS \"Value\" FROM pragma_table_info('TeachingTaskScheduleConstraints')")
            .ToListAsync(cancellationToken))
            .ToHashSet(StringComparer.OrdinalIgnoreCase);
        await ApplyMigrationAsync(
            SeparateExperimentClassroomScopeMigration,
            experimentScopeColumns.Contains("ExperimentRequiredCampusId")
                ? []
                : SeparateExperimentClassroomScopeStatements,
            cancellationToken);
        var courseGroupsExist = await db.Database
            .SqlQueryRaw<int>(
                "SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'CourseGroups'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ReusableCourseGroupsMigration,
            courseGroupsExist ? [] : ReusableCourseGroupsStatements,
            cancellationToken);
        var experimentCourseGradesExist = await db.Database
            .SqlQueryRaw<int>(
                "SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'ExperimentCourseGrades'")
            .AnyAsync(value => value > 0, cancellationToken);
        await ApplyMigrationAsync(
            ExperimentCourseGradesMigration,
            experimentCourseGradesExist ? [] : ExperimentCourseGradesStatements,
            cancellationToken);
        await ApplyMigrationAsync(
            NotificationInboxIndexesMigration,
            NotificationInboxIndexesStatements,
            cancellationToken);
        var experimentProjectColumns = (await db.Database.SqlQueryRaw<string>(
                "SELECT name AS \"Value\" FROM pragma_table_info('ExperimentProjects')")
            .ToListAsync(cancellationToken))
            .ToHashSet(StringComparer.OrdinalIgnoreCase);
        var experimentSessionInstructorsExist = await db.Database
            .SqlQueryRaw<int>(
                "SELECT COUNT(*) AS \"Value\" FROM sqlite_master WHERE type = 'table' AND name = 'ExperimentSessionInstructors'")
            .AnyAsync(value => value > 0, cancellationToken);
        var selfScheduledExperimentSelectionStatements = new List<string>();
        if (!experimentProjectColumns.Contains("SelectionStartsAt"))
            selfScheduledExperimentSelectionStatements.Add(SelfScheduledExperimentSelectionStatements[0]);
        if (!experimentProjectColumns.Contains("SelectionEndsAt"))
            selfScheduledExperimentSelectionStatements.Add(SelfScheduledExperimentSelectionStatements[1]);
        if (!experimentSessionInstructorsExist)
            selfScheduledExperimentSelectionStatements.AddRange(SelfScheduledExperimentSelectionStatements.Skip(2));
        await ApplyMigrationAsync(
            SelfScheduledExperimentSelectionMigration,
            selfScheduledExperimentSelectionStatements,
            cancellationToken);
    }

    private async Task ApplyMigrationAsync(
        string migrationId,
        IEnumerable<string> statements,
        CancellationToken cancellationToken)
    {
        var applied = await db.Database
            .SqlQuery<string>(
                $"""
                 SELECT "MigrationId" AS "Value"
                 FROM "__DevelopmentSchemaHistory"
                 WHERE "MigrationId" = {migrationId}
                 """)
            .AnyAsync(cancellationToken);
        if (applied)
        {
            return;
        }

        await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
        foreach (var statement in statements)
        {
            await db.Database.ExecuteSqlRawAsync(statement, cancellationToken);
        }

        await db.Database.ExecuteSqlInterpolatedAsync(
            $"""
             INSERT INTO "__DevelopmentSchemaHistory" ("MigrationId", "AppliedAt")
             VALUES ({migrationId}, {DateTime.UtcNow});
             """,
            cancellationToken);
        await transaction.CommitAsync(cancellationToken);
        logger.LogInformation(
            "Applied SQLite development schema migration {MigrationId}.",
            migrationId);
    }

    private static readonly string[] PeopleAndCoursesStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "Teachers" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_Teachers" PRIMARY KEY,
            "TeacherNumber" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "Gender" INTEGER NOT NULL,
            "CollegeId" TEXT NOT NULL,
            "Title" TEXT NULL,
            "Status" INTEGER NOT NULL,
            "HireDate" TEXT NULL,
            "IsExternal" INTEGER NOT NULL,
            "Phone" TEXT NULL,
            "Email" TEXT NULL,
            "Notes" TEXT NULL,
            "UserId" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_Teachers_Colleges_CollegeId"
                FOREIGN KEY ("CollegeId") REFERENCES "Colleges" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_Teachers_AspNetUsers_UserId"
                FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE SET NULL
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_Teachers_TeacherNumber"
            ON "Teachers" ("TeacherNumber");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_Teachers_CollegeId_Status"
            ON "Teachers" ("CollegeId", "Status");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_Teachers_UserId"
            ON "Teachers" ("UserId");
        """,
        """
        CREATE TABLE IF NOT EXISTS "Students" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_Students" PRIMARY KEY,
            "StudentNumber" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "Gender" INTEGER NOT NULL,
            "AdministrativeClassId" TEXT NOT NULL,
            "EnrollmentYear" INTEGER NOT NULL,
            "EnrollmentDate" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "DateOfBirth" TEXT NULL,
            "Phone" TEXT NULL,
            "Email" TEXT NULL,
            "Notes" TEXT NULL,
            "UserId" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_Students_AdministrativeClasses_AdministrativeClassId"
                FOREIGN KEY ("AdministrativeClassId") REFERENCES "AdministrativeClasses" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_Students_AspNetUsers_UserId"
                FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE SET NULL
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_Students_StudentNumber"
            ON "Students" ("StudentNumber");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_Students_AdministrativeClassId_Status"
            ON "Students" ("AdministrativeClassId", "Status");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_Students_EnrollmentYear"
            ON "Students" ("EnrollmentYear");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_Students_UserId"
            ON "Students" ("UserId");
        """,
        """
        CREATE TABLE IF NOT EXISTS "Courses" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_Courses" PRIMARY KEY,
            "CollegeId" TEXT NOT NULL,
            "EnglishName" TEXT NULL,
            "Credits" TEXT NOT NULL,
            "TotalHours" INTEGER NOT NULL,
            "LectureHours" INTEGER NOT NULL,
            "PracticeHours" INTEGER NOT NULL,
            "Nature" INTEGER NOT NULL,
            "AssessmentMethod" INTEGER NOT NULL,
            "Description" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            "Code" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "SortOrder" INTEGER NOT NULL,
            "IsEnabled" INTEGER NOT NULL,
            CONSTRAINT "FK_Courses_Colleges_CollegeId"
                FOREIGN KEY ("CollegeId") REFERENCES "Colleges" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_Courses_Code" ON "Courses" ("Code");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_Courses_IsEnabled_SortOrder"
            ON "Courses" ("IsEnabled", "SortOrder");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_Courses_CollegeId_Nature"
            ON "Courses" ("CollegeId", "Nature");
        """
    ];

    private static readonly string[] CurriculumPlansStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "CurriculumPlans" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CurriculumPlans" PRIMARY KEY,
            "MajorId" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "Version" TEXT NOT NULL,
            "EffectiveGrade" INTEGER NOT NULL,
            "TotalCredits" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "Description" TEXT NULL,
            "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_CurriculumPlans_Majors_MajorId"
                FOREIGN KEY ("MajorId") REFERENCES "Majors" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_CurriculumPlans_MajorId_EffectiveGrade_Version"
            ON "CurriculumPlans" ("MajorId", "EffectiveGrade", "Version");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_CurriculumPlans_Status_EffectiveGrade"
            ON "CurriculumPlans" ("Status", "EffectiveGrade");
        """,
        """
        CREATE TABLE IF NOT EXISTS "CurriculumModules" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CurriculumModules" PRIMARY KEY,
            "CurriculumPlanId" TEXT NOT NULL,
            "Code" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "RequiredCredits" TEXT NOT NULL,
            "SortOrder" INTEGER NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_CurriculumModules_CurriculumPlans_CurriculumPlanId"
                FOREIGN KEY ("CurriculumPlanId") REFERENCES "CurriculumPlans" ("Id")
                ON DELETE CASCADE
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_CurriculumModules_CurriculumPlanId_Code"
            ON "CurriculumModules" ("CurriculumPlanId", "Code");
        """,
        """
        CREATE TABLE IF NOT EXISTS "CurriculumCourses" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CurriculumCourses" PRIMARY KEY,
            "CurriculumModuleId" TEXT NOT NULL,
            "CourseId" TEXT NOT NULL,
            "RecommendedSemester" INTEGER NOT NULL,
            "Type" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_CurriculumCourses_CurriculumModules_CurriculumModuleId"
                FOREIGN KEY ("CurriculumModuleId") REFERENCES "CurriculumModules" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_CurriculumCourses_Courses_CourseId"
                FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_CurriculumCourses_CurriculumModuleId_CourseId"
            ON "CurriculumCourses" ("CurriculumModuleId", "CourseId");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_CurriculumCourses_CourseId"
            ON "CurriculumCourses" ("CourseId");
        """
    ];

    private static readonly string[] TeachingTasksStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "TeachingTasks" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_TeachingTasks" PRIMARY KEY,
            "TaskNumber" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "AcademicTermId" TEXT NOT NULL,
            "CourseId" TEXT NOT NULL,
            "Capacity" INTEGER NOT NULL,
            "StartWeek" INTEGER NOT NULL,
            "EndWeek" INTEGER NOT NULL,
             "WeeklyHours" INTEGER NOT NULL,
             "SchedulingMode" INTEGER NOT NULL DEFAULT 1,
             "Status" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_TeachingTasks_AcademicTerms_AcademicTermId"
                FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_TeachingTasks_Courses_CourseId"
                FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_TeachingTasks_TaskNumber"
            ON "TeachingTasks" ("TaskNumber");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_TeachingTasks_AcademicTermId_Status"
            ON "TeachingTasks" ("AcademicTermId", "Status");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_TeachingTasks_CourseId"
            ON "TeachingTasks" ("CourseId");
        """,
        """
        CREATE TABLE IF NOT EXISTS "TeachingTaskTeachers" (
            "TeachingTaskId" TEXT NOT NULL,
            "TeacherId" TEXT NOT NULL,
            "IsPrimary" INTEGER NOT NULL,
            CONSTRAINT "PK_TeachingTaskTeachers"
                PRIMARY KEY ("TeachingTaskId", "TeacherId"),
            CONSTRAINT "FK_TeachingTaskTeachers_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_TeachingTaskTeachers_Teachers_TeacherId"
                FOREIGN KEY ("TeacherId") REFERENCES "Teachers" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_TeachingTaskTeachers_TeacherId"
            ON "TeachingTaskTeachers" ("TeacherId");
        """,
        """
        CREATE TABLE IF NOT EXISTS "TeachingTaskClasses" (
            "TeachingTaskId" TEXT NOT NULL,
            "AdministrativeClassId" TEXT NOT NULL,
            CONSTRAINT "PK_TeachingTaskClasses"
                PRIMARY KEY ("TeachingTaskId", "AdministrativeClassId"),
            CONSTRAINT "FK_TeachingTaskClasses_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_TeachingTaskClasses_AdministrativeClasses_AdministrativeClassId"
                FOREIGN KEY ("AdministrativeClassId") REFERENCES "AdministrativeClasses" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_TeachingTaskClasses_AdministrativeClassId"
            ON "TeachingTaskClasses" ("AdministrativeClassId");
        """
    ];

    private static readonly string[] SchedulesStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "SchedulePlans" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_SchedulePlans" PRIMARY KEY,
            "AcademicTermId" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "Version" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_SchedulePlans_AcademicTerms_AcademicTermId"
                FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_SchedulePlans_AcademicTermId_Version"
            ON "SchedulePlans" ("AcademicTermId", "Version");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_SchedulePlans_AcademicTermId_Status"
            ON "SchedulePlans" ("AcademicTermId", "Status");
        """,
        """
        CREATE TABLE IF NOT EXISTS "ScheduleEntries" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ScheduleEntries" PRIMARY KEY,
            "SchedulePlanId" TEXT NOT NULL,
            "TeachingTaskId" TEXT NOT NULL,
            "ClassroomId" TEXT NOT NULL,
            "DayOfWeek" INTEGER NOT NULL,
            "StartPeriod" INTEGER NOT NULL,
            "PeriodCount" INTEGER NOT NULL,
            "StartWeek" INTEGER NOT NULL,
            "EndWeek" INTEGER NOT NULL,
            "WeekPattern" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ScheduleEntries_SchedulePlans_SchedulePlanId"
                FOREIGN KEY ("SchedulePlanId") REFERENCES "SchedulePlans" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_ScheduleEntries_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_ScheduleEntries_Classrooms_ClassroomId"
                FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_ScheduleEntries_SchedulePlanId_DayOfWeek_StartPeriod"
            ON "ScheduleEntries" ("SchedulePlanId", "DayOfWeek", "StartPeriod");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_ScheduleEntries_TeachingTaskId"
            ON "ScheduleEntries" ("TeachingTaskId");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_ScheduleEntries_ClassroomId"
            ON "ScheduleEntries" ("ClassroomId");
        """
    ];

    private static readonly string[] ClassCounselorStatements =
    [
        """
        ALTER TABLE "AdministrativeClasses"
            ADD COLUMN "CounselorUserId" TEXT NULL;
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_AdministrativeClasses_CounselorUserId"
            ON "AdministrativeClasses" ("CounselorUserId");
        """
    ];

    private static readonly string[] CourseSelectionStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "CourseSelectionRounds" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CourseSelectionRounds" PRIMARY KEY,
            "AcademicTermId" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "StartsAt" TEXT NOT NULL,
            "EndsAt" TEXT NOT NULL,
            "WithdrawalEndsAt" TEXT NOT NULL,
            "MaxCredits" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_CourseSelectionRounds_AcademicTerms_AcademicTermId"
                FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_CourseSelectionRounds_AcademicTermId_Status"
            ON "CourseSelectionRounds" ("AcademicTermId", "Status");
        """,
        """
        CREATE TABLE IF NOT EXISTS "CourseSelectionOfferings" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CourseSelectionOfferings" PRIMARY KEY,
            "CourseSelectionRoundId" TEXT NOT NULL,
            "TeachingTaskId" TEXT NOT NULL,
            "Capacity" INTEGER NOT NULL,
            "IsOpenToAll" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_CourseSelectionOfferings_CourseSelectionRounds_CourseSelectionRoundId"
                FOREIGN KEY ("CourseSelectionRoundId") REFERENCES "CourseSelectionRounds" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_CourseSelectionOfferings_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_CourseSelectionOfferings_CourseSelectionRoundId_TeachingTaskId"
            ON "CourseSelectionOfferings" ("CourseSelectionRoundId", "TeachingTaskId");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_CourseSelectionOfferings_TeachingTaskId"
            ON "CourseSelectionOfferings" ("TeachingTaskId");
        """,
        """
        CREATE TABLE IF NOT EXISTS "CourseEnrollments" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CourseEnrollments" PRIMARY KEY,
            "CourseSelectionOfferingId" TEXT NOT NULL,
            "StudentId" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "EnrolledAt" TEXT NOT NULL,
            "WithdrawnAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_CourseEnrollments_CourseSelectionOfferings_CourseSelectionOfferingId"
                FOREIGN KEY ("CourseSelectionOfferingId") REFERENCES "CourseSelectionOfferings" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_CourseEnrollments_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_CourseEnrollments_CourseSelectionOfferingId_StudentId"
            ON "CourseEnrollments" ("CourseSelectionOfferingId", "StudentId");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_CourseEnrollments_StudentId_Status"
            ON "CourseEnrollments" ("StudentId", "Status");
        """
    ];

    private static readonly string[] GradesStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "GradeSheets" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GradeSheets" PRIMARY KEY,
            "TeachingTaskId" TEXT NOT NULL,
            "RegularWeight" TEXT NOT NULL,
            "FinalWeight" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "ReviewComment" TEXT NULL,
            "SubmittedAt" TEXT NULL,
            "ReviewedAt" TEXT NULL,
            "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_GradeSheets_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_GradeSheets_TeachingTaskId"
            ON "GradeSheets" ("TeachingTaskId");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_GradeSheets_Status"
            ON "GradeSheets" ("Status");
        """,
        """
        CREATE TABLE IF NOT EXISTS "GradeRecords" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GradeRecords" PRIMARY KEY,
            "GradeSheetId" TEXT NOT NULL,
            "StudentId" TEXT NOT NULL,
            "RegularScore" TEXT NULL,
            "FinalScore" TEXT NULL,
            "TotalScore" TEXT NULL,
            "GradePoint" TEXT NULL,
            "ExamStatus" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_GradeRecords_GradeSheets_GradeSheetId"
                FOREIGN KEY ("GradeSheetId") REFERENCES "GradeSheets" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_GradeRecords_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_GradeRecords_GradeSheetId_StudentId"
            ON "GradeRecords" ("GradeSheetId", "StudentId");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_GradeRecords_StudentId_TotalScore"
            ON "GradeRecords" ("StudentId", "TotalScore");
        """
    ];

    private static readonly string[] ExamsStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "ExamPlans" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExamPlans" PRIMARY KEY,
            "AcademicTermId" TEXT NOT NULL, "Name" TEXT NOT NULL,
            "Status" INTEGER NOT NULL, "Notes" TEXT NULL, "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExamPlans_AcademicTerms_AcademicTermId"
              FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT
        );
        """,
        """CREATE INDEX IF NOT EXISTS "IX_ExamPlans_AcademicTermId_Status" ON "ExamPlans" ("AcademicTermId", "Status");""",
        """
        CREATE TABLE IF NOT EXISTS "ExamSessions" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExamSessions" PRIMARY KEY,
            "ExamPlanId" TEXT NOT NULL, "TeachingTaskId" TEXT NOT NULL,
            "ClassroomId" TEXT NOT NULL, "StartsAt" TEXT NOT NULL, "EndsAt" TEXT NOT NULL,
            "Notes" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExamSessions_ExamPlans_ExamPlanId" FOREIGN KEY ("ExamPlanId")
              REFERENCES "ExamPlans" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_ExamSessions_TeachingTasks_TeachingTaskId" FOREIGN KEY ("TeachingTaskId")
              REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_ExamSessions_Classrooms_ClassroomId" FOREIGN KEY ("ClassroomId")
              REFERENCES "Classrooms" ("Id") ON DELETE RESTRICT
        );
        """,
        """CREATE INDEX IF NOT EXISTS "IX_ExamSessions_ExamPlanId_StartsAt" ON "ExamSessions" ("ExamPlanId", "StartsAt");""",
        """CREATE INDEX IF NOT EXISTS "IX_ExamSessions_TeachingTaskId" ON "ExamSessions" ("TeachingTaskId");""",
        """CREATE INDEX IF NOT EXISTS "IX_ExamSessions_ClassroomId" ON "ExamSessions" ("ClassroomId");""",
        """
        CREATE TABLE IF NOT EXISTS "ExamSessionInvigilators" (
            "ExamSessionId" TEXT NOT NULL, "TeacherId" TEXT NOT NULL,
            CONSTRAINT "PK_ExamSessionInvigilators" PRIMARY KEY ("ExamSessionId", "TeacherId"),
            CONSTRAINT "FK_ExamSessionInvigilators_ExamSessions_ExamSessionId"
              FOREIGN KEY ("ExamSessionId") REFERENCES "ExamSessions" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_ExamSessionInvigilators_Teachers_TeacherId"
              FOREIGN KEY ("TeacherId") REFERENCES "Teachers" ("Id") ON DELETE RESTRICT
        );
        """,
        """CREATE INDEX IF NOT EXISTS "IX_ExamSessionInvigilators_TeacherId" ON "ExamSessionInvigilators" ("TeacherId");"""
    ];

    private static readonly string[] FlexibleGradesNewStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "GradeItems" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GradeItems" PRIMARY KEY,
            "GradeSheetId" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "Weight" TEXT NOT NULL,
            "SortOrder" INTEGER NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_GradeItems_GradeSheets_GradeSheetId"
                FOREIGN KEY ("GradeSheetId") REFERENCES "GradeSheets" ("Id") ON DELETE CASCADE
        );
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_GradeItems_GradeSheetId_SortOrder"
            ON "GradeItems" ("GradeSheetId", "SortOrder");
        """,
        """
        CREATE TABLE IF NOT EXISTS "GradeItemScores" (
            "GradeRecordId" TEXT NOT NULL,
            "GradeItemId" TEXT NOT NULL,
            "Score" TEXT NULL,
            CONSTRAINT "PK_GradeItemScores" PRIMARY KEY ("GradeRecordId", "GradeItemId"),
            CONSTRAINT "FK_GradeItemScores_GradeRecords_GradeRecordId"
                FOREIGN KEY ("GradeRecordId") REFERENCES "GradeRecords" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_GradeItemScores_GradeItems_GradeItemId"
                FOREIGN KEY ("GradeItemId") REFERENCES "GradeItems" ("Id") ON DELETE RESTRICT
        );
        """
    ];

    private static readonly string[] FlexibleGradesUpgradeStatements =
    [
        """
        CREATE TABLE "GradeSheets_v2" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GradeSheets" PRIMARY KEY,
            "TeachingTaskId" TEXT NOT NULL,
            "RegularWeight" TEXT NOT NULL,
            "FinalWeight" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "ReviewComment" TEXT NULL,
            "SubmittedAt" TEXT NULL,
            "ReviewedAt" TEXT NULL,
            "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_GradeSheets_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        INSERT INTO "GradeSheets_v2" ("Id","TeachingTaskId","RegularWeight","FinalWeight",
            "Status","ReviewComment","SubmittedAt","ReviewedAt","PublishedAt","CreatedAt","UpdatedAt")
        SELECT "Id","TeachingTaskId","RegularWeight","FinalWeight",
            "Status","ReviewComment","SubmittedAt","ReviewedAt","PublishedAt","CreatedAt","UpdatedAt"
        FROM "GradeSheets";
        """,
        "DROP TABLE \"GradeSheets\";",
        "ALTER TABLE \"GradeSheets_v2\" RENAME TO \"GradeSheets\";",
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_GradeSheets_TeachingTaskId"
            ON "GradeSheets" ("TeachingTaskId");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_GradeSheets_Status"
            ON "GradeSheets" ("Status");
        """,
        """
        CREATE TABLE "GradeRecords_v2" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GradeRecords" PRIMARY KEY,
            "GradeSheetId" TEXT NOT NULL,
            "StudentId" TEXT NOT NULL,
            "RegularScore" TEXT NULL,
            "FinalScore" TEXT NULL,
            "TotalScore" TEXT NULL,
            "GradePoint" TEXT NULL,
            "ExamStatus" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_GradeRecords_GradeSheets_GradeSheetId"
                FOREIGN KEY ("GradeSheetId") REFERENCES "GradeSheets" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_GradeRecords_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        INSERT INTO "GradeRecords_v2" ("Id","GradeSheetId","StudentId","RegularScore","FinalScore",
            "TotalScore","GradePoint","ExamStatus","Notes","CreatedAt","UpdatedAt")
        SELECT "Id","GradeSheetId","StudentId","RegularScore","FinalScore",
            "TotalScore","GradePoint","ExamStatus","Notes","CreatedAt","UpdatedAt"
        FROM "GradeRecords";
        """,
        "DROP TABLE \"GradeRecords\";",
        "ALTER TABLE \"GradeRecords_v2\" RENAME TO \"GradeRecords\";",
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_GradeRecords_GradeSheetId_StudentId"
            ON "GradeRecords" ("GradeSheetId", "StudentId");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_GradeRecords_StudentId_TotalScore"
            ON "GradeRecords" ("StudentId", "TotalScore");
        """,
        """
        CREATE TABLE IF NOT EXISTS "GradeItems" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GradeItems" PRIMARY KEY,
            "GradeSheetId" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "Weight" TEXT NOT NULL,
            "SortOrder" INTEGER NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_GradeItems_GradeSheets_GradeSheetId"
                FOREIGN KEY ("GradeSheetId") REFERENCES "GradeSheets" ("Id") ON DELETE CASCADE
        );
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_GradeItems_GradeSheetId_SortOrder"
            ON "GradeItems" ("GradeSheetId", "SortOrder");
        """,
        """
        CREATE TABLE IF NOT EXISTS "GradeItemScores" (
            "GradeRecordId" TEXT NOT NULL,
            "GradeItemId" TEXT NOT NULL,
            "Score" TEXT NULL,
            CONSTRAINT "PK_GradeItemScores" PRIMARY KEY ("GradeRecordId", "GradeItemId"),
            CONSTRAINT "FK_GradeItemScores_GradeRecords_GradeRecordId"
                FOREIGN KEY ("GradeRecordId") REFERENCES "GradeRecords" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_GradeItemScores_GradeItems_GradeItemId"
                FOREIGN KEY ("GradeItemId") REFERENCES "GradeItems" ("Id") ON DELETE RESTRICT
        );
        """
    ];

    private static readonly string[] AttendanceStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "AttendanceSheets" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_AttendanceSheets" PRIMARY KEY,
            "TeachingTaskId" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "AttendanceDate" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "SubmittedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_AttendanceSheets_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_AttendanceSheets_TeachingTaskId_AttendanceDate"
            ON "AttendanceSheets" ("TeachingTaskId", "AttendanceDate");
        """,
        """
        CREATE TABLE IF NOT EXISTS "AttendanceRecords" (
            "AttendanceSheetId" TEXT NOT NULL,
            "StudentId" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            CONSTRAINT "PK_AttendanceRecords" PRIMARY KEY ("AttendanceSheetId", "StudentId"),
            CONSTRAINT "FK_AttendanceRecords_AttendanceSheets_AttendanceSheetId"
                FOREIGN KEY ("AttendanceSheetId") REFERENCES "AttendanceSheets" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_AttendanceRecords_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_AttendanceRecords_AttendanceSheetId_StudentId"
            ON "AttendanceRecords" ("AttendanceSheetId", "StudentId");
        """
    ];

    private static readonly string[] StudentStatusChangesStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "StudentStatusChanges" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_StudentStatusChanges" PRIMARY KEY,
            "StudentId" TEXT NOT NULL, "Type" INTEGER NOT NULL,
            "OriginalStatus" INTEGER NOT NULL, "TargetStatus" INTEGER NOT NULL,
            "Reason" TEXT NOT NULL, "State" INTEGER NOT NULL,
            "ReviewComment" TEXT NULL, "SubmittedAt" TEXT NOT NULL,
            "ReviewedAt" TEXT NULL, "ApprovedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_StudentStatusChanges_Students_StudentId"
              FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT
        );
        """,
        """CREATE INDEX IF NOT EXISTS "IX_StudentStatusChanges_StudentId_State" ON "StudentStatusChanges" ("StudentId", "State");"""
    ];

    private static readonly string[] GraduationAuditsStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "GraduationAuditBatches" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GraduationAuditBatches" PRIMARY KEY,
            "Name" TEXT NOT NULL, "GraduationYear" INTEGER NOT NULL,
            "EnrollmentYear" INTEGER NOT NULL, "Status" INTEGER NOT NULL,
            "Notes" TEXT NULL, "CalculatedAt" TEXT NULL, "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL
        );
        """,
        """CREATE INDEX IF NOT EXISTS "IX_GraduationAuditBatches_GraduationYear_EnrollmentYear" ON "GraduationAuditBatches" ("GraduationYear", "EnrollmentYear");""",
        """CREATE INDEX IF NOT EXISTS "IX_GraduationAuditBatches_Status" ON "GraduationAuditBatches" ("Status");""",
        """
        CREATE TABLE IF NOT EXISTS "GraduationAuditResults" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GraduationAuditResults" PRIMARY KEY,
            "GraduationAuditBatchId" TEXT NOT NULL, "StudentId" TEXT NOT NULL,
            "CurriculumPlanId" TEXT NULL, "StudentStatusSnapshot" INTEGER NOT NULL,
            "RequiredCredits" TEXT NOT NULL, "EarnedCredits" TEXT NOT NULL,
            "RequiredCourseCount" INTEGER NOT NULL,
            "PassedRequiredCourseCount" INTEGER NOT NULL,
            "FailedCourseCount" INTEGER NOT NULL,
            "MissingCourseNames" TEXT NOT NULL,
            "CalculatedConclusion" INTEGER NOT NULL, "Conclusion" INTEGER NOT NULL,
            "IsOverridden" INTEGER NOT NULL, "ReviewComment" TEXT NULL,
            "ReviewedAt" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_GraduationAuditResults_GraduationAuditBatches_GraduationAuditBatchId"
              FOREIGN KEY ("GraduationAuditBatchId") REFERENCES "GraduationAuditBatches" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_GraduationAuditResults_Students_StudentId"
              FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_GraduationAuditResults_CurriculumPlans_CurriculumPlanId"
              FOREIGN KEY ("CurriculumPlanId") REFERENCES "CurriculumPlans" ("Id") ON DELETE SET NULL
        );
        """,
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_GraduationAuditResults_GraduationAuditBatchId_StudentId" ON "GraduationAuditResults" ("GraduationAuditBatchId", "StudentId");""",
        """CREATE INDEX IF NOT EXISTS "IX_GraduationAuditResults_StudentId" ON "GraduationAuditResults" ("StudentId");""",
        """CREATE INDEX IF NOT EXISTS "IX_GraduationAuditResults_CurriculumPlanId" ON "GraduationAuditResults" ("CurriculumPlanId");""",
        """CREATE INDEX IF NOT EXISTS "IX_GraduationAuditResults_Conclusion_IsOverridden" ON "GraduationAuditResults" ("Conclusion", "IsOverridden");"""
    ];

    private static readonly string[] DegreeAwardsStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "DegreeAwardBatches" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_DegreeAwardBatches" PRIMARY KEY,
            "Name" TEXT NOT NULL, "GraduationYear" INTEGER NOT NULL,
            "DegreeName" TEXT NOT NULL, "MinimumGradePoint" TEXT NOT NULL,
            "Status" INTEGER NOT NULL, "Notes" TEXT NULL,
            "CalculatedAt" TEXT NULL, "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL
        );
        """,
        """CREATE INDEX IF NOT EXISTS "IX_DegreeAwardBatches_GraduationYear_Status" ON "DegreeAwardBatches" ("GraduationYear", "Status");""",
        """
        CREATE TABLE IF NOT EXISTS "DegreeAwardResults" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_DegreeAwardResults" PRIMARY KEY,
            "DegreeAwardBatchId" TEXT NOT NULL, "StudentId" TEXT NOT NULL,
            "GraduationAuditResultId" TEXT NOT NULL, "AverageGradePoint" TEXT NOT NULL,
            "CalculatedConclusion" INTEGER NOT NULL, "Conclusion" INTEGER NOT NULL,
            "ExceptionReason" TEXT NOT NULL, "IsOverridden" INTEGER NOT NULL,
            "ReviewComment" TEXT NULL, "ReviewedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_DegreeAwardResults_DegreeAwardBatches_DegreeAwardBatchId"
              FOREIGN KEY ("DegreeAwardBatchId") REFERENCES "DegreeAwardBatches" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_DegreeAwardResults_Students_StudentId"
              FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_DegreeAwardResults_GraduationAuditResults_GraduationAuditResultId"
              FOREIGN KEY ("GraduationAuditResultId") REFERENCES "GraduationAuditResults" ("Id") ON DELETE RESTRICT
        );
        """,
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_DegreeAwardResults_DegreeAwardBatchId_StudentId" ON "DegreeAwardResults" ("DegreeAwardBatchId", "StudentId");""",
        """CREATE INDEX IF NOT EXISTS "IX_DegreeAwardResults_StudentId" ON "DegreeAwardResults" ("StudentId");""",
        """CREATE INDEX IF NOT EXISTS "IX_DegreeAwardResults_GraduationAuditResultId" ON "DegreeAwardResults" ("GraduationAuditResultId");""",
        """CREATE INDEX IF NOT EXISTS "IX_DegreeAwardResults_Conclusion_IsOverridden" ON "DegreeAwardResults" ("Conclusion", "IsOverridden");"""
    ];

    private static readonly string[] GraduationClearanceStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "GraduationClearanceBatches" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GraduationClearanceBatches" PRIMARY KEY,
            "Name" TEXT NOT NULL, "GraduationYear" INTEGER NOT NULL,
            "Status" INTEGER NOT NULL, "Notes" TEXT NULL, "ClosedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL
        );
        """,
        """CREATE INDEX IF NOT EXISTS "IX_GraduationClearanceBatches_GraduationYear_Status" ON "GraduationClearanceBatches" ("GraduationYear", "Status");""",
        """
        CREATE TABLE IF NOT EXISTS "GraduationClearanceItems" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GraduationClearanceItems" PRIMARY KEY,
            "GraduationClearanceBatchId" TEXT NOT NULL, "Code" TEXT NOT NULL,
            "Name" TEXT NOT NULL, "ResponsibleUnit" TEXT NOT NULL,
            "ResponsibleRole" TEXT NOT NULL, "IsRequired" INTEGER NOT NULL,
            "SortOrder" INTEGER NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_GraduationClearanceItems_GraduationClearanceBatches_GraduationClearanceBatchId"
              FOREIGN KEY ("GraduationClearanceBatchId") REFERENCES "GraduationClearanceBatches" ("Id") ON DELETE CASCADE
        );
        """,
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_GraduationClearanceItems_GraduationClearanceBatchId_Code" ON "GraduationClearanceItems" ("GraduationClearanceBatchId", "Code");""",
        """
        CREATE TABLE IF NOT EXISTS "GraduationClearanceRecords" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_GraduationClearanceRecords" PRIMARY KEY,
            "GraduationClearanceItemId" TEXT NOT NULL, "StudentId" TEXT NOT NULL,
            "Status" INTEGER NOT NULL, "Notes" TEXT NULL, "CompletedAt" TEXT NULL,
            "CompletedByUserId" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_GraduationClearanceRecords_GraduationClearanceItems_GraduationClearanceItemId"
              FOREIGN KEY ("GraduationClearanceItemId") REFERENCES "GraduationClearanceItems" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_GraduationClearanceRecords_Students_StudentId"
              FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT
        );
        """,
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_GraduationClearanceRecords_GraduationClearanceItemId_StudentId" ON "GraduationClearanceRecords" ("GraduationClearanceItemId", "StudentId");""",
        """CREATE INDEX IF NOT EXISTS "IX_GraduationClearanceRecords_StudentId_Status" ON "GraduationClearanceRecords" ("StudentId", "Status");"""
    ];

    private static readonly string[] CourseCategoriesStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "CourseCategories" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CourseCategories" PRIMARY KEY,
            "Code" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "SortOrder" INTEGER NOT NULL,
            "IsEnabled" INTEGER NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_CourseCategories_Code"
            ON "CourseCategories" ("Code");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_CourseCategories_IsEnabled_SortOrder"
            ON "CourseCategories" ("IsEnabled", "SortOrder");
        """,
        """
        ALTER TABLE "Courses" ADD COLUMN "CourseCategoryId" TEXT NULL;
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_Courses_CourseCategoryId"
            ON "Courses" ("CourseCategoryId");
        """
    ];

    private static readonly string[] SchedulingOptimizationStatements =
    [
        """
        CREATE TABLE "ScheduleEntries_New" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ScheduleEntries" PRIMARY KEY,
            "SchedulePlanId" TEXT NOT NULL,
            "TeachingTaskId" TEXT NOT NULL,
            "ClassroomId" TEXT NULL,
            "DayOfWeek" INTEGER NOT NULL,
            "StartPeriod" INTEGER NOT NULL,
            "PeriodCount" INTEGER NOT NULL,
            "StartWeek" INTEGER NOT NULL,
            "EndWeek" INTEGER NOT NULL,
            "WeekPattern" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ScheduleEntries_SchedulePlans_SchedulePlanId"
                FOREIGN KEY ("SchedulePlanId") REFERENCES "SchedulePlans" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_ScheduleEntries_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_ScheduleEntries_Classrooms_ClassroomId"
                FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id")
                ON DELETE SET NULL
        );
        """,
        """
        INSERT INTO "ScheduleEntries_New"
        SELECT "Id", "SchedulePlanId", "TeachingTaskId", "ClassroomId",
               "DayOfWeek", "StartPeriod", "PeriodCount", "StartWeek", "EndWeek",
               "WeekPattern", "Notes", "CreatedAt", "UpdatedAt"
        FROM "ScheduleEntries";
        """,
        """DROP TABLE "ScheduleEntries";""",
        """ALTER TABLE "ScheduleEntries_New" RENAME TO "ScheduleEntries";""",
        """
        CREATE INDEX "IX_ScheduleEntries_SchedulePlanId_DayOfWeek_StartPeriod"
            ON "ScheduleEntries" ("SchedulePlanId", "DayOfWeek", "StartPeriod");
        """,
        """
        CREATE INDEX "IX_ScheduleEntries_TeachingTaskId"
            ON "ScheduleEntries" ("TeachingTaskId");
        """,
        """
        CREATE INDEX "IX_ScheduleEntries_ClassroomId"
            ON "ScheduleEntries" ("ClassroomId");
        """,
        """
        CREATE TABLE "ScheduleTimeSlots" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ScheduleTimeSlots" PRIMARY KEY,
            "AcademicTermId" TEXT NOT NULL,
            "PeriodNumber" INTEGER NOT NULL,
            "Name" TEXT NOT NULL,
            "StartsAt" TEXT NOT NULL,
            "EndsAt" TEXT NOT NULL,
            "IsEnabled" INTEGER NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ScheduleTimeSlots_AcademicTerms_AcademicTermId"
                FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id")
                ON DELETE CASCADE
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_ScheduleTimeSlots_AcademicTermId_PeriodNumber"
            ON "ScheduleTimeSlots" ("AcademicTermId", "PeriodNumber");
        """,
        """
        CREATE TABLE "TeachingTaskScheduleConstraints" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_TeachingTaskScheduleConstraints" PRIMARY KEY,
            "TeachingTaskId" TEXT NOT NULL,
            "RequiresClassroom" INTEGER NOT NULL,
            "RequiredCampusId" TEXT NULL,
            "RequiredBuildingId" TEXT NULL,
            "AllowedDayOfWeeks" TEXT NULL,
            "EarliestPeriod" INTEGER NULL,
            "LatestPeriod" INTEGER NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_TeachingTaskScheduleConstraints_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_TeachingTaskScheduleConstraints_Campuses_RequiredCampusId"
                FOREIGN KEY ("RequiredCampusId") REFERENCES "Campuses" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_TeachingTaskScheduleConstraints_Buildings_RequiredBuildingId"
                FOREIGN KEY ("RequiredBuildingId") REFERENCES "Buildings" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_TeachingTaskScheduleConstraints_TeachingTaskId"
            ON "TeachingTaskScheduleConstraints" ("TeachingTaskId");
        """,
        """
        CREATE INDEX "IX_TeachingTaskScheduleConstraints_RequiredCampusId"
            ON "TeachingTaskScheduleConstraints" ("RequiredCampusId");
        """,
        """
        CREATE INDEX "IX_TeachingTaskScheduleConstraints_RequiredBuildingId"
            ON "TeachingTaskScheduleConstraints" ("RequiredBuildingId");
        """,
        """
        CREATE TABLE "TeachingTaskAllowedClassrooms" (
            "TeachingTaskScheduleConstraintId" TEXT NOT NULL,
            "ClassroomId" TEXT NOT NULL,
            CONSTRAINT "PK_TeachingTaskAllowedClassrooms"
                PRIMARY KEY ("TeachingTaskScheduleConstraintId", "ClassroomId"),
            CONSTRAINT "FK_TeachingTaskAllowedClassrooms_Constraints"
                FOREIGN KEY ("TeachingTaskScheduleConstraintId")
                REFERENCES "TeachingTaskScheduleConstraints" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_TeachingTaskAllowedClassrooms_Classrooms_ClassroomId"
                FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX "IX_TeachingTaskAllowedClassrooms_ClassroomId"
            ON "TeachingTaskAllowedClassrooms" ("ClassroomId");
        """
    ];

    private static readonly string[] TeacherCourseApplicationStatements =
    [
        """
        ALTER TABLE "TeachingTasks" ADD COLUMN "GenerationBatchCode" TEXT NULL;
        """,
        """
        CREATE TABLE "TeacherCourseApplications" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_TeacherCourseApplications" PRIMARY KEY,
            "AcademicTermId" TEXT NOT NULL,
            "TeacherId" TEXT NOT NULL,
            "CourseId" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "Statement" TEXT NULL,
            "ReviewComment" TEXT NULL,
            "SubmittedAt" TEXT NOT NULL,
            "ReviewedAt" TEXT NULL,
            "ReviewedByUserId" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_TeacherCourseApplications_AcademicTerms"
                FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_TeacherCourseApplications_Teachers"
                FOREIGN KEY ("TeacherId") REFERENCES "Teachers" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_TeacherCourseApplications_Courses"
                FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_TeacherCourseApplications_ReviewedBy"
                FOREIGN KEY ("ReviewedByUserId") REFERENCES "AspNetUsers" ("Id")
                ON DELETE SET NULL
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_TeacherCourseApplications_Term_Teacher_Course"
            ON "TeacherCourseApplications" ("AcademicTermId", "TeacherId", "CourseId");
        """,
        """
        CREATE INDEX "IX_TeacherCourseApplications_Status_AcademicTermId"
            ON "TeacherCourseApplications" ("Status", "AcademicTermId");
        """,
        """
        CREATE INDEX "IX_TeacherCourseApplications_TeacherId"
            ON "TeacherCourseApplications" ("TeacherId");
        """,
        """
        CREATE INDEX "IX_TeacherCourseApplications_CourseId"
            ON "TeacherCourseApplications" ("CourseId");
        """,
        """
        CREATE INDEX "IX_TeacherCourseApplications_ReviewedByUserId"
            ON "TeacherCourseApplications" ("ReviewedByUserId");
        """
    ];

    private static readonly string[] AutomaticScheduleJobStatements =
    [
        """
        CREATE TABLE "AutomaticScheduleJobs" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_AutomaticScheduleJobs" PRIMARY KEY,
            "SchedulePlanId" TEXT NOT NULL,
            "ActiveSchedulePlanId" TEXT NULL,
            "RequestedByUserId" TEXT NULL,
            "Status" INTEGER NOT NULL,
            "TotalTasks" INTEGER NOT NULL,
            "ProcessedTasks" INTEGER NOT NULL,
            "CreatedEntries" INTEGER NOT NULL,
            "CompletedTasks" INTEGER NOT NULL,
            "MessagesJson" TEXT NULL,
            "ErrorMessage" TEXT NULL,
            "StartedAt" TEXT NULL,
            "CompletedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_AutomaticScheduleJobs_SchedulePlans"
                FOREIGN KEY ("SchedulePlanId") REFERENCES "SchedulePlans" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_AutomaticScheduleJobs_RequestedBy"
                FOREIGN KEY ("RequestedByUserId") REFERENCES "AspNetUsers" ("Id")
                ON DELETE SET NULL
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_AutomaticScheduleJobs_ActiveSchedulePlanId"
            ON "AutomaticScheduleJobs" ("ActiveSchedulePlanId");
        """,
        """
        CREATE INDEX "IX_AutomaticScheduleJobs_SchedulePlanId_CreatedAt"
            ON "AutomaticScheduleJobs" ("SchedulePlanId", "CreatedAt");
        """,
        """
        CREATE INDEX "IX_AutomaticScheduleJobs_Status_CreatedAt"
            ON "AutomaticScheduleJobs" ("Status", "CreatedAt");
        """,
        """
        CREATE INDEX "IX_AutomaticScheduleJobs_RequestedByUserId"
            ON "AutomaticScheduleJobs" ("RequestedByUserId");
        """
    ];

    private static readonly string[] TeachingTaskSchedulingModeStatements =
    [
        """
        ALTER TABLE "TeachingTasks"
        ADD COLUMN "SchedulingMode" INTEGER NOT NULL DEFAULT 1;
        """
    ];

    private static readonly string[] SchedulePublishJobStatements =
    [
        """
        CREATE TABLE "SchedulePublishJobs" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_SchedulePublishJobs" PRIMARY KEY,
            "SchedulePlanId" TEXT NOT NULL,
            "AcademicTermId" TEXT NOT NULL,
            "ActiveAcademicTermId" TEXT NULL,
            "RequestedByUserId" TEXT NULL,
            "Status" INTEGER NOT NULL,
            "TotalSteps" INTEGER NOT NULL,
            "CompletedSteps" INTEGER NOT NULL,
            "CurrentStep" TEXT NULL,
            "ErrorMessage" TEXT NULL,
            "StartedAt" TEXT NULL,
            "CompletedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_SchedulePublishJobs_SchedulePlans"
                FOREIGN KEY ("SchedulePlanId") REFERENCES "SchedulePlans" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_SchedulePublishJobs_RequestedBy"
                FOREIGN KEY ("RequestedByUserId") REFERENCES "AspNetUsers" ("Id")
                ON DELETE SET NULL
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_SchedulePublishJobs_ActiveAcademicTermId"
            ON "SchedulePublishJobs" ("ActiveAcademicTermId");
        """,
        """
        CREATE INDEX "IX_SchedulePublishJobs_SchedulePlanId_CreatedAt"
            ON "SchedulePublishJobs" ("SchedulePlanId", "CreatedAt");
        """,
        """
        CREATE INDEX "IX_SchedulePublishJobs_Status_CreatedAt"
            ON "SchedulePublishJobs" ("Status", "CreatedAt");
        """,
        """
        CREATE INDEX "IX_SchedulePublishJobs_RequestedByUserId"
            ON "SchedulePublishJobs" ("RequestedByUserId");
        """
    ];

    private static readonly string[] ExamSchedulingOptimizationStatements =
    [
        """
        ALTER TABLE "ExamSessions" ADD COLUMN "ExamDate" TEXT NOT NULL DEFAULT '2027-01-01';
        """,
        """
        ALTER TABLE "ExamSessions" ADD COLUMN "StartPeriod" INTEGER NOT NULL DEFAULT 1;
        """,
        """
        ALTER TABLE "ExamSessions" ADD COLUMN "PeriodCount" INTEGER NOT NULL DEFAULT 2;
        """,
        """
        ALTER TABLE "ExamSessions" ADD COLUMN "RequiredBuildingId" TEXT NULL;
        """,
        """
        ALTER TABLE "ExamSessions" ADD COLUMN "RequiredBuildingIds" TEXT NULL;
        """,
        """
        ALTER TABLE "ExamSessions" ADD COLUMN "RequiredInvigilatorCount" INTEGER NOT NULL DEFAULT 2;
        """,
        """
        CREATE TABLE "ExamSessions_Temp" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExamSessions" PRIMARY KEY,
            "ExamPlanId" TEXT NOT NULL,
            "TeachingTaskId" TEXT NOT NULL,
            "ClassroomId" TEXT NULL,
            "ExamDate" TEXT NOT NULL,
            "StartPeriod" INTEGER NOT NULL,
            "PeriodCount" INTEGER NOT NULL,
            "StartsAt" TEXT NOT NULL,
            "EndsAt" TEXT NOT NULL,
            "RequiredBuildingId" TEXT NULL,
            "RequiredBuildingIds" TEXT NULL,
            "RequiredInvigilatorCount" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExamSessions_ExamPlans_ExamPlanId"
                FOREIGN KEY ("ExamPlanId") REFERENCES "ExamPlans" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_ExamSessions_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_ExamSessions_Classrooms_ClassroomId"
                FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id") ON DELETE SET NULL,
            CONSTRAINT "FK_ExamSessions_Buildings_RequiredBuildingId"
                FOREIGN KEY ("RequiredBuildingId") REFERENCES "Buildings" ("Id") ON DELETE SET NULL
        );
        """,
        """
        INSERT INTO "ExamSessions_Temp"
            ("Id","ExamPlanId","TeachingTaskId","ClassroomId","ExamDate",
             "StartPeriod","PeriodCount","StartsAt","EndsAt",
             "RequiredBuildingId","RequiredInvigilatorCount",
             "Notes","CreatedAt","UpdatedAt")
        SELECT "Id","ExamPlanId","TeachingTaskId","ClassroomId",
               '2027-01-01',
               1,2,
               "StartsAt","EndsAt",
               NULL,2,
               "Notes","CreatedAt","UpdatedAt"
        FROM "ExamSessions";
        """,
        "DROP TABLE \"ExamSessions\";",
        "ALTER TABLE \"ExamSessions_Temp\" RENAME TO \"ExamSessions\";",
        """
        CREATE INDEX "IX_ExamSessions_ExamPlanId_StartsAt"
            ON "ExamSessions" ("ExamPlanId", "StartsAt");
        """,
        """
        CREATE INDEX "IX_ExamSessions_TeachingTaskId"
            ON "ExamSessions" ("TeachingTaskId");
        """,
        """
        CREATE INDEX "IX_ExamSessions_ExamPlanId_ExamDate"
            ON "ExamSessions" ("ExamPlanId", "ExamDate");
        """,
        """
        CREATE INDEX "IX_ExamSessions_RequiredBuildingId"
            ON "ExamSessions" ("RequiredBuildingId");
        """
    ];

    private static readonly string[] RetakeEnrollmentStatements =
    [
        """
        ALTER TABLE "CourseEnrollments"
        ADD COLUMN "EnrollmentType" INTEGER NOT NULL DEFAULT 1;
        """
    ];

    private static readonly string[] CourseSelectionWaitlistStatements =
    [
        """
        ALTER TABLE "CourseEnrollments"
        ADD COLUMN "WaitlistedAt" TEXT NULL;
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_CE_Offering_Status_WaitlistedAt"
        ON "CourseEnrollments" ("CourseSelectionOfferingId", "Status", "WaitlistedAt");
        """
    ];

    private static readonly string[] PersonalCalendarSubscriptionStatements =
    [
        """
        ALTER TABLE "AspNetUsers"
        ADD COLUMN "CalendarSubscriptionStamp" TEXT NULL;
        """,
        """
        ALTER TABLE "AspNetUsers"
        ADD COLUMN "CalendarSubscriptionCreatedAt" TEXT NULL;
        """
    ];

    private static readonly string[] OfficialDocumentStatements =
    [
        """
        CREATE TABLE "OfficialDocuments" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_OfficialDocuments" PRIMARY KEY,
            "DocumentNumber" TEXT NOT NULL,
            "VerificationCodeHash" TEXT NOT NULL,
            "Type" INTEGER NOT NULL,
            "Status" INTEGER NOT NULL,
            "StudentId" TEXT NOT NULL,
            "IssuedByUserId" TEXT NOT NULL,
            "IssuedAt" TEXT NOT NULL,
            "Purpose" TEXT NULL,
            "SnapshotJson" TEXT NOT NULL,
            "PdfContent" BLOB NOT NULL,
            "PdfSha256" TEXT NOT NULL,
            "InvalidatedAt" TEXT NULL,
            "InvalidatedByUserId" TEXT NULL,
            "InvalidationReason" TEXT NULL,
            "ReissuedFromDocumentId" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_OfficialDocuments_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_OfficialDocuments_AspNetUsers_IssuedByUserId"
                FOREIGN KEY ("IssuedByUserId") REFERENCES "AspNetUsers" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_OfficialDocuments_AspNetUsers_InvalidatedByUserId"
                FOREIGN KEY ("InvalidatedByUserId") REFERENCES "AspNetUsers" ("Id") ON DELETE RESTRICT,
            CONSTRAINT "FK_OfficialDocuments_ReissuedFromDocumentId"
                FOREIGN KEY ("ReissuedFromDocumentId") REFERENCES "OfficialDocuments" ("Id") ON DELETE RESTRICT
        );
        """,
        """CREATE UNIQUE INDEX "IX_OfficialDocuments_DocumentNumber" ON "OfficialDocuments" ("DocumentNumber");""",
        """CREATE UNIQUE INDEX "IX_OfficialDocuments_VerificationCodeHash" ON "OfficialDocuments" ("VerificationCodeHash");""",
        """CREATE INDEX "IX_OfficialDocuments_StudentId_IssuedAt" ON "OfficialDocuments" ("StudentId", "IssuedAt");""",
        """CREATE INDEX "IX_OfficialDocuments_Status_IssuedAt" ON "OfficialDocuments" ("Status", "IssuedAt");""",
        """CREATE INDEX "IX_OfficialDocuments_IssuedByUserId" ON "OfficialDocuments" ("IssuedByUserId");""",
        """CREATE INDEX "IX_OfficialDocuments_InvalidatedByUserId" ON "OfficialDocuments" ("InvalidatedByUserId");""",
        """CREATE UNIQUE INDEX "IX_OfficialDocuments_ReissuedFromDocumentId" ON "OfficialDocuments" ("ReissuedFromDocumentId");""",
        """
        CREATE TABLE "OfficialDocumentDownloads" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_OfficialDocumentDownloads" PRIMARY KEY,
            "OfficialDocumentId" TEXT NOT NULL,
            "DownloadedByUserId" TEXT NOT NULL,
            "IpAddress" TEXT NULL,
            "UserAgent" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_OfficialDocumentDownloads_OfficialDocuments"
                FOREIGN KEY ("OfficialDocumentId") REFERENCES "OfficialDocuments" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_OfficialDocumentDownloads_AspNetUsers"
                FOREIGN KEY ("DownloadedByUserId") REFERENCES "AspNetUsers" ("Id") ON DELETE RESTRICT
        );
        """,
        """CREATE INDEX "IX_OfficialDocumentDownloads_OfficialDocumentId_CreatedAt" ON "OfficialDocumentDownloads" ("OfficialDocumentId", "CreatedAt");""",
        """CREATE INDEX "IX_OfficialDocumentDownloads_DownloadedByUserId_CreatedAt" ON "OfficialDocumentDownloads" ("DownloadedByUserId", "CreatedAt");"""
    ];

    private static readonly string[] CourseAdjustmentsStatements =
    [
        """
        CREATE TABLE "CourseAdjustments" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CourseAdjustments" PRIMARY KEY,
            "TeachingTaskId" TEXT NOT NULL,
            "Type" INTEGER NOT NULL,
            "Status" INTEGER NOT NULL,
            "ApplicantUserId" TEXT NOT NULL,
            "SourceScheduleEntryId" TEXT NULL,
            "SourceWeek" INTEGER NULL,
            "SourceDate" TEXT NULL,
            "SourceStartPeriod" INTEGER NULL,
            "SourcePeriodCount" INTEGER NULL,
            "SourceClassroomId" TEXT NULL,
            "TargetDate" TEXT NULL,
            "DayOfWeek" INTEGER NULL,
            "StartPeriod" INTEGER NULL,
            "PeriodCount" INTEGER NULL,
            "ClassroomId" TEXT NULL,
            "SubstituteTeacherId" TEXT NULL,
            "CancelWeek" INTEGER NULL,
            "CancelDate" TEXT NULL,
            "Reason" TEXT NOT NULL,
            "ReviewComment" TEXT NULL,
            "SubmittedAt" TEXT NULL,
            "ReviewedAt" TEXT NULL,
            "ReviewedByUserId" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_CourseAdjustments_TeachingTasks"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_CourseAdjustments_Classrooms"
                FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id")
                ON DELETE SET NULL,
            CONSTRAINT "FK_CourseAdjustments_Teachers"
                FOREIGN KEY ("SubstituteTeacherId") REFERENCES "Teachers" ("Id")
                ON DELETE SET NULL
        );
        """,
        """CREATE INDEX "IX_CourseAdjustments_TeachingTaskId_Status" ON "CourseAdjustments" ("TeachingTaskId", "Status");""",
        """CREATE INDEX "IX_CourseAdjustments_ApplicantUserId" ON "CourseAdjustments" ("ApplicantUserId");""",
        """CREATE INDEX "IX_CourseAdjustments_Status_CreatedAt" ON "CourseAdjustments" ("Status", "CreatedAt");""",
        """
        CREATE TABLE "Notifications" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_Notifications" PRIMARY KEY,
            "UserId" TEXT NOT NULL,
            "Title" TEXT NOT NULL,
            "Content" TEXT NOT NULL,
            "IsRead" INTEGER NOT NULL,
            "LinkUrl" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL
        );
        """,
        """CREATE INDEX "IX_Notifications_UserId_IsRead" ON "Notifications" ("UserId", "IsRead");""",
        """CREATE INDEX "IX_Notifications_CreatedAt" ON "Notifications" ("CreatedAt");"""
    ];

    private static readonly string[] CourseAdjustmentOccurrencesStatements =
    [
        """ALTER TABLE "CourseAdjustments" ADD "SourceScheduleEntryId" TEXT NULL;""",
        """ALTER TABLE "CourseAdjustments" ADD "SourceWeek" INTEGER NULL;""",
        """ALTER TABLE "CourseAdjustments" ADD "SourceDate" TEXT NULL;""",
        """ALTER TABLE "CourseAdjustments" ADD "SourceStartPeriod" INTEGER NULL;""",
        """ALTER TABLE "CourseAdjustments" ADD "SourcePeriodCount" INTEGER NULL;""",
        """ALTER TABLE "CourseAdjustments" ADD "SourceClassroomId" TEXT NULL;""",
        """CREATE INDEX "IX_CourseAdjustments_SourceScheduleEntryId_SourceWeek" ON "CourseAdjustments" ("SourceScheduleEntryId", "SourceWeek");"""
    ];

    private static readonly string[] AttendanceAppealStatements =
    [
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "AppealStatus" INTEGER NOT NULL DEFAULT 0;""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "AppealReason" TEXT NULL;""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "AppealSubmittedAt" TEXT NULL;""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "AppealReviewComment" TEXT NULL;""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "AppealReviewedAt" TEXT NULL;""",
        """CREATE INDEX IF NOT EXISTS "IX_AttendanceRecords_AppealStatus" ON "AttendanceRecords" ("AppealStatus");"""
    ];

    private static readonly string[] AttendanceCheckInStatements =
    [
        """ALTER TABLE "AttendanceSheets" ADD COLUMN "CheckInMethod" INTEGER NOT NULL DEFAULT 1;""",
        """ALTER TABLE "AttendanceSheets" ADD COLUMN "CheckInToken" TEXT NULL;""",
        """ALTER TABLE "AttendanceSheets" ADD COLUMN "CheckInStartsAt" TEXT NULL;""",
        """ALTER TABLE "AttendanceSheets" ADD COLUMN "CheckInEndsAt" TEXT NULL;""",
        """ALTER TABLE "AttendanceSheets" ADD COLUMN "TargetLatitude" TEXT NULL;""",
        """ALTER TABLE "AttendanceSheets" ADD COLUMN "TargetLongitude" TEXT NULL;""",
        """ALTER TABLE "AttendanceSheets" ADD COLUMN "LocationRadiusMeters" INTEGER NULL;""",
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_AttendanceSheets_CheckInToken" ON "AttendanceSheets" ("CheckInToken");""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "CheckInAt" TEXT NULL;""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "CheckedInMethod" INTEGER NULL;""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "CheckInLatitude" TEXT NULL;""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "CheckInLongitude" TEXT NULL;""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "CheckInAccuracyMeters" REAL NULL;""",
        """ALTER TABLE "AttendanceRecords" ADD COLUMN "CheckInDistanceMeters" REAL NULL;"""
    ];

    private static readonly string[] AttendanceCheckInAuditStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "AttendanceCheckInAttempts" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_AttendanceCheckInAttempts" PRIMARY KEY,
            "AttendanceSheetId" TEXT NOT NULL,
            "StudentId" TEXT NOT NULL,
            "CheckInMethod" INTEGER NOT NULL,
            "IsSuccessful" INTEGER NOT NULL,
            "FailureCode" TEXT NULL,
            "DeviceIdentifierHash" TEXT NULL,
            "DevicePlatform" TEXT NULL,
            "IpAddress" TEXT NULL,
            "UserAgent" TEXT NULL,
            "RiskFlags" TEXT NULL,
            "Latitude" TEXT NULL,
            "Longitude" TEXT NULL,
            "AccuracyMeters" REAL NULL,
            "DistanceMeters" REAL NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_AttendanceCheckInAttempts_AttendanceSheets_AttendanceSheetId"
                FOREIGN KEY ("AttendanceSheetId") REFERENCES "AttendanceSheets" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_AttendanceCheckInAttempts_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_AttendanceCheckInAttempts_AttendanceSheetId_StudentId_CreatedAt"
            ON "AttendanceCheckInAttempts" ("AttendanceSheetId", "StudentId", "CreatedAt");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_AttendanceCheckInAttempts_DeviceIdentifierHash_CreatedAt"
            ON "AttendanceCheckInAttempts" ("DeviceIdentifierHash", "CreatedAt");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_AttendanceCheckInAttempts_IpAddress_CreatedAt"
            ON "AttendanceCheckInAttempts" ("IpAddress", "CreatedAt");
        """
    ];

    private static readonly string[] AppUpdateReleasesStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "AppUpdateReleases" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_AppUpdateReleases" PRIMARY KEY,
            "Platform" TEXT NOT NULL,
            "Channel" TEXT NOT NULL,
            "Version" TEXT NOT NULL,
            "NativeVersion" TEXT NOT NULL,
            "Status" TEXT NOT NULL,
            "ReleaseNotes" TEXT NULL,
            "FileName" TEXT NOT NULL,
            "FileSize" INTEGER NOT NULL,
            "Sha256" TEXT NOT NULL,
            "BundleContent" BLOB NOT NULL,
            "CreatedByUserName" TEXT NOT NULL,
            "PublishedByUserName" TEXT NULL,
            "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS
            "IX_AppUpdateReleases_Platform_Channel_NativeVersion_Version"
            ON "AppUpdateReleases"
                ("Platform", "Channel", "NativeVersion", "Version");
        """,
        """
        CREATE INDEX IF NOT EXISTS
            "IX_AppUpdateReleases_Platform_Channel_NativeVersion_Status"
            ON "AppUpdateReleases"
                ("Platform", "Channel", "NativeVersion", "Status");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_AppUpdateReleases_CreatedAt"
            ON "AppUpdateReleases" ("CreatedAt");
        """
    ];

    private static readonly string[] RefreshSessionsStatements =
    [
        """
        CREATE TABLE IF NOT EXISTS "RefreshSessions" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_RefreshSessions" PRIMARY KEY,
            "UserId" TEXT NOT NULL,
            "TokenHash" TEXT NOT NULL,
            "ClientType" TEXT NOT NULL,
            "SecurityStamp" TEXT NOT NULL,
            "ExpiresAt" TEXT NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "LastRefreshedAt" TEXT NOT NULL,
            "RevokedAt" TEXT NULL,
            "ReplacedBySessionId" TEXT NULL,
            CONSTRAINT "FK_RefreshSessions_AspNetUsers_UserId"
                FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
        );
        """,
        """
        CREATE UNIQUE INDEX IF NOT EXISTS "IX_RefreshSessions_TokenHash"
            ON "RefreshSessions" ("TokenHash");
        """,
        """
        CREATE INDEX IF NOT EXISTS "IX_RefreshSessions_UserId_ExpiresAt"
            ON "RefreshSessions" ("UserId", "ExpiresAt");
        """
    ];

    private static readonly string[] StudentPersonalProfileStatements =
    [
        """ALTER TABLE "Students" ADD COLUMN "Biography" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "CurrentAddress" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "EmergencyContactName" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "EmergencyContactPhone" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "EmergencyContactRelationship" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "EnglishName" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "Ethnicity" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "HouseholdAddress" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "IdCardNumber" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "Nationality" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "NativePlace" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "PoliticalStatus" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "PostalCode" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "Qq" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "SpecialNeeds" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "SpecialTags" TEXT NULL;""",
        """ALTER TABLE "Students" ADD COLUMN "WeChat" TEXT NULL;"""
    ];

    private static readonly string[] OtherExamResultsStatements =
    [
        """ALTER TABLE "OtherExamBatches" ADD COLUMN "ExamCode" TEXT NULL;""",
        """CREATE TABLE IF NOT EXISTS "OtherExamBatches" ("Id" TEXT NOT NULL CONSTRAINT "PK_OtherExamBatches" PRIMARY KEY, "ExamCode" TEXT NULL, "Name" TEXT NOT NULL, "Organizer" TEXT NULL, "ExamDate" TEXT NOT NULL, "MetricKind" INTEGER NOT NULL, "MaxScore" TEXT NULL, "LevelOptions" TEXT NULL, "Status" INTEGER NOT NULL, "PublicationCount" INTEGER NOT NULL, "PublishedAt" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL);""",
        """CREATE INDEX IF NOT EXISTS "IX_OtherExamBatches_Status_ExamDate" ON "OtherExamBatches" ("Status", "ExamDate");""",
        """CREATE TABLE IF NOT EXISTS "OtherExamResults" ("Id" TEXT NOT NULL CONSTRAINT "PK_OtherExamResults" PRIMARY KEY, "OtherExamBatchId" TEXT NOT NULL, "StudentId" TEXT NOT NULL, "AttemptNumber" INTEGER NOT NULL, "Score" TEXT NULL, "Level" TEXT NULL, "IsPassed" INTEGER NULL, "Notes" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_OtherExamResults_OtherExamBatches" FOREIGN KEY ("OtherExamBatchId") REFERENCES "OtherExamBatches" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_OtherExamResults_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT);""",
        """DROP INDEX IF EXISTS "IX_OtherExamResults_OtherExamBatchId_StudentId_AttemptNumber";""",
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_OtherExamResults_OtherExamBatchId_StudentId" ON "OtherExamResults" ("OtherExamBatchId", "StudentId");""",
        """CREATE INDEX IF NOT EXISTS "IX_OtherExamResults_StudentId_OtherExamBatchId" ON "OtherExamResults" ("StudentId", "OtherExamBatchId");"""
    ];

    private static readonly string[] CourseGradeStatisticsStatements =
    [
        """CREATE TABLE IF NOT EXISTS "CourseGradeStatistics" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseGradeStatistics" PRIMARY KEY, "CourseId" TEXT NOT NULL, "AcademicTermId" TEXT NOT NULL, "Scope" INTEGER NOT NULL, "ScopeEntityId" TEXT NULL, "StudentCount" INTEGER NOT NULL, "PassedCount" INTEGER NOT NULL, "HighestScore" TEXT NOT NULL, "AverageScore" TEXT NOT NULL, "LowestScore" TEXT NOT NULL, "PassRate" TEXT NOT NULL, "CalculatedAt" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_CourseGradeStatistics_Courses_CourseId" FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_CourseGradeStatistics_AcademicTerms_AcademicTermId" FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT);""",
        """CREATE UNIQUE INDEX IF NOT EXISTS "UX_CourseGradeStatistics_Scope" ON "CourseGradeStatistics" ("CourseId", "AcademicTermId", "Scope", "ScopeEntityId");""",
        """CREATE INDEX IF NOT EXISTS "IX_CourseGradeStatistics_AcademicTermId_Scope_ScopeEntityId" ON "CourseGradeStatistics" ("AcademicTermId", "Scope", "ScopeEntityId");""",
        """CREATE TABLE IF NOT EXISTS "CourseGradeStatisticsRefreshJobs" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseGradeStatisticsRefreshJobs" PRIMARY KEY, "GradeSheetId" TEXT NOT NULL, "Status" INTEGER NOT NULL, "StartedAt" TEXT NULL, "CompletedAt" TEXT NULL, "ErrorMessage" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_CourseGradeStatisticsRefreshJobs_GradeSheets_GradeSheetId" FOREIGN KEY ("GradeSheetId") REFERENCES "GradeSheets" ("Id") ON DELETE CASCADE);""",
        """CREATE INDEX IF NOT EXISTS "IX_CourseGradeStatisticsRefreshJobs_GradeSheetId" ON "CourseGradeStatisticsRefreshJobs" ("GradeSheetId");""",
        """CREATE INDEX IF NOT EXISTS "IX_CourseGradeStatisticsRefreshJobs_Status_CreatedAt" ON "CourseGradeStatisticsRefreshJobs" ("Status", "CreatedAt");"""
    ];

    private static readonly string[] CourseGradeDistributionStatements =
    [
        """ALTER TABLE "CourseGradeStatistics" ADD COLUMN "Below60Count" INTEGER NOT NULL DEFAULT 0;""",
        """ALTER TABLE "CourseGradeStatistics" ADD COLUMN "From60To69Count" INTEGER NOT NULL DEFAULT 0;""",
        """ALTER TABLE "CourseGradeStatistics" ADD COLUMN "From70To79Count" INTEGER NOT NULL DEFAULT 0;""",
        """ALTER TABLE "CourseGradeStatistics" ADD COLUMN "From80To89Count" INTEGER NOT NULL DEFAULT 0;""",
        """ALTER TABLE "CourseGradeStatistics" ADD COLUMN "From90To100Count" INTEGER NOT NULL DEFAULT 0;"""
    ];

    private static readonly string[] CourseGradeDistributionColumns =
    [
        "Below60Count",
        "From60To69Count",
        "From70To79Count",
        "From80To89Count",
        "From90To100Count"
    ];

    private static readonly string[] TeachingTaskGradeAnalyticsStatements =
    [
        """CREATE TABLE IF NOT EXISTS "TeachingTaskGradeStatistics" ("Id" TEXT NOT NULL CONSTRAINT "PK_TeachingTaskGradeStatistics" PRIMARY KEY, "GradeSheetId" TEXT NOT NULL, "TeachingTaskId" TEXT NOT NULL, "CourseId" TEXT NOT NULL, "AcademicTermId" TEXT NOT NULL, "StudentCount" INTEGER NOT NULL, "PassedCount" INTEGER NOT NULL, "ExcellentCount" INTEGER NOT NULL, "HighestScore" TEXT NOT NULL, "AverageScore" TEXT NOT NULL, "MedianScore" TEXT NOT NULL, "LowestScore" TEXT NOT NULL, "StandardDeviation" TEXT NOT NULL, "PassRate" TEXT NOT NULL, "ExcellentRate" TEXT NOT NULL, "CalculatedAt" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_TeachingTaskGradeStatistics_GradeSheets" FOREIGN KEY ("GradeSheetId") REFERENCES "GradeSheets" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_TeachingTaskGradeStatistics_TeachingTasks" FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_TeachingTaskGradeStatistics_Courses" FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_TeachingTaskGradeStatistics_AcademicTerms" FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT);""",
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_TeachingTaskGradeStatistics_GradeSheetId" ON "TeachingTaskGradeStatistics" ("GradeSheetId");""",
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_TeachingTaskGradeStatistics_TeachingTaskId" ON "TeachingTaskGradeStatistics" ("TeachingTaskId");""",
        """CREATE INDEX IF NOT EXISTS "IX_TeachingTaskGradeStatistics_CourseId_AcademicTermId" ON "TeachingTaskGradeStatistics" ("CourseId", "AcademicTermId");""",
        """CREATE INDEX IF NOT EXISTS "IX_TeachingTaskGradeStatistics_AcademicTermId" ON "TeachingTaskGradeStatistics" ("AcademicTermId");""",
        """CREATE TABLE IF NOT EXISTS "TeachingTaskGradeScoreBands" ("Id" TEXT NOT NULL CONSTRAINT "PK_TeachingTaskGradeScoreBands" PRIMARY KEY, "TeachingTaskGradeStatisticId" TEXT NOT NULL, "Label" TEXT NOT NULL, "LowerBound" TEXT NOT NULL, "UpperBound" TEXT NULL, "StudentCount" INTEGER NOT NULL, "SortOrder" INTEGER NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_TeachingTaskGradeScoreBands_Statistics" FOREIGN KEY ("TeachingTaskGradeStatisticId") REFERENCES "TeachingTaskGradeStatistics" ("Id") ON DELETE CASCADE);""",
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_TeachingTaskGradeScoreBands_StatisticId_SortOrder" ON "TeachingTaskGradeScoreBands" ("TeachingTaskGradeStatisticId", "SortOrder");"""
    ];

    private static readonly string[] ApprovalTableStatements =
    [
        """CREATE TABLE "CourseExemptions" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseExemptions" PRIMARY KEY, "StudentId" TEXT NOT NULL, "TeachingTaskId" TEXT NOT NULL, "Reason" TEXT NOT NULL, "Status" INTEGER NOT NULL, "ReviewComment" TEXT NULL, "SubmittedAt" TEXT NOT NULL, "ReviewedAt" TEXT NULL, "ReviewedByUserId" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_CourseExemptions_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_CourseExemptions_TeachingTasks" FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT);""",
        """CREATE UNIQUE INDEX "IX_CourseExemptions_StudentId_TeachingTaskId" ON "CourseExemptions" ("StudentId", "TeachingTaskId");""",
        """CREATE INDEX "IX_CourseExemptions_Status_CreatedAt" ON "CourseExemptions" ("Status", "CreatedAt");""",

        """CREATE TABLE "DeferredExams" ("Id" TEXT NOT NULL CONSTRAINT "PK_DeferredExams" PRIMARY KEY, "StudentId" TEXT NOT NULL, "TeachingTaskId" TEXT NOT NULL, "Reason" TEXT NOT NULL, "Status" INTEGER NOT NULL, "ReviewComment" TEXT NULL, "SubmittedAt" TEXT NOT NULL, "ReviewedAt" TEXT NULL, "ReviewedByUserId" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_DeferredExams_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_DeferredExams_TeachingTasks" FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT);""",
        """CREATE UNIQUE INDEX "IX_DeferredExams_StudentId_TeachingTaskId" ON "DeferredExams" ("StudentId", "TeachingTaskId");""",
        """CREATE INDEX "IX_DeferredExams_Status_CreatedAt" ON "DeferredExams" ("Status", "CreatedAt");""",

        """CREATE TABLE "GradeModifications" ("Id" TEXT NOT NULL CONSTRAINT "PK_GradeModifications" PRIMARY KEY, "GradeRecordId" TEXT NOT NULL, "CurrentScore" TEXT NOT NULL, "RequestedScore" TEXT NOT NULL, "Reason" TEXT NOT NULL, "Status" INTEGER NOT NULL, "ReviewComment" TEXT NULL, "ApplicantUserId" TEXT NOT NULL, "SubmittedAt" TEXT NOT NULL, "CollegeReviewedAt" TEXT NULL, "CollegeReviewedByUserId" TEXT NULL, "FinalReviewedAt" TEXT NULL, "FinalReviewedByUserId" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_GradeModifications_GradeRecords" FOREIGN KEY ("GradeRecordId") REFERENCES "GradeRecords" ("Id") ON DELETE RESTRICT);""",
        """CREATE INDEX "IX_GradeModifications_Status_CreatedAt" ON "GradeModifications" ("Status", "CreatedAt");""",

        """CREATE TABLE "CourseSubstitutions" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseSubstitutions" PRIMARY KEY, "StudentId" TEXT NOT NULL, "OriginalCourseId" TEXT NOT NULL, "SubstituteCourseId" TEXT NOT NULL, "Reason" TEXT NOT NULL, "Status" INTEGER NOT NULL, "ReviewComment" TEXT NULL, "SubmittedAt" TEXT NOT NULL, "ReviewedAt" TEXT NULL, "ReviewedByUserId" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_CourseSubstitutions_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_CourseSubstitutions_OriginalCourse" FOREIGN KEY ("OriginalCourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_CourseSubstitutions_SubstituteCourse" FOREIGN KEY ("SubstituteCourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT);""",
        """CREATE UNIQUE INDEX "IX_CourseSubstitutions_StudentId_OriginalCourseId" ON "CourseSubstitutions" ("StudentId", "OriginalCourseId");""",
        """CREATE INDEX "IX_CourseSubstitutions_Status_CreatedAt" ON "CourseSubstitutions" ("Status", "CreatedAt");"""
    ];

    private static readonly string[] AcademicWarningStatements =
    [
        """CREATE TABLE "WarningRules" ("Id" TEXT NOT NULL CONSTRAINT "PK_WarningRules" PRIMARY KEY, "Type" INTEGER NOT NULL, "Name" TEXT NOT NULL, "Threshold" TEXT NOT NULL, "IsEnabled" INTEGER NOT NULL, "NotifyStudent" INTEGER NOT NULL, "NotifyCounselor" INTEGER NOT NULL, "AcademicTermId" TEXT NOT NULL, "Description" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_WarningRules_AcademicTerms" FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE CASCADE);""",
        """CREATE UNIQUE INDEX "IX_WarningRules_AcademicTermId_Type" ON "WarningRules" ("AcademicTermId", "Type");""",
        """CREATE TABLE "WarningRecords" ("Id" TEXT NOT NULL CONSTRAINT "PK_WarningRecords" PRIMARY KEY, "StudentId" TEXT NOT NULL, "Type" INTEGER NOT NULL, "Status" INTEGER NOT NULL, "TriggerValue" TEXT NOT NULL, "Detail" TEXT NOT NULL, "AcknowledgedAt" TEXT NULL, "AcknowledgeComment" TEXT NULL, "AcademicTermId" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "FK_WarningRecords_Students" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT);""",
        """CREATE UNIQUE INDEX "IX_WarningRecords_StudentId_AcademicTermId_Type" ON "WarningRecords" ("StudentId", "AcademicTermId", "Type");""",
        """CREATE INDEX "IX_WarningRecords_Status" ON "WarningRecords" ("Status");""",
        """ALTER TABLE "WarningRules" ADD COLUMN "AutoCheckEnabled" INTEGER NOT NULL DEFAULT 0;""",
        """ALTER TABLE "WarningRules" ADD COLUMN "CheckDayOfWeek" INTEGER NULL;""",
        """ALTER TABLE "WarningRules" ADD COLUMN "CheckHour" INTEGER NOT NULL DEFAULT 8;""",
        """ALTER TABLE "WarningRules" ADD COLUMN "CheckMinute" INTEGER NOT NULL DEFAULT 0;""",
        """ALTER TABLE "WarningRules" ADD COLUMN "LastCheckAt" TEXT NULL;"""
    ];

    private static readonly string[] AcademicTermArchivingStatements =
    [
        """ALTER TABLE "AcademicTerms" ADD COLUMN "IsArchived" INTEGER NOT NULL DEFAULT 0;""",
        """ALTER TABLE "AcademicTerms" ADD COLUMN "ArchivedAt" TEXT NULL;""",
        """CREATE INDEX IF NOT EXISTS "IX_AcademicTerms_IsArchived" ON "AcademicTerms" ("IsArchived");"""
    ];

    private const string TeachingEvaluationMigration = "TeachingEvaluation";

    private static readonly string[] TeachingEvaluationStatements =
    [
        """CREATE TABLE "EvaluationSetups" ("Id" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, "AcademicTermId" TEXT NOT NULL, "Name" TEXT NOT NULL, "Status" INTEGER NOT NULL, "StartsAt" TEXT NULL, "EndsAt" TEXT NULL, CONSTRAINT "PK_EvaluationSetups" PRIMARY KEY ("Id"), CONSTRAINT "FK_EvaluationSetups_AcademicTerms_AcademicTermId" FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT);""",
        """CREATE INDEX "IX_EvaluationSetups_AcademicTermId_Status" ON "EvaluationSetups" ("AcademicTermId", "Status");""",
        """CREATE TABLE "EvaluationDimensions" ("Id" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, "EvaluationSetupId" TEXT NOT NULL, "Name" TEXT NOT NULL, "MaxScore" INTEGER NOT NULL, "SortOrder" INTEGER NOT NULL, CONSTRAINT "PK_EvaluationDimensions" PRIMARY KEY ("Id"), CONSTRAINT "FK_EvaluationDimensions_EvaluationSetups_EvaluationSetupId" FOREIGN KEY ("EvaluationSetupId") REFERENCES "EvaluationSetups" ("Id") ON DELETE CASCADE);""",
        """CREATE INDEX "IX_EvaluationDimensions_EvaluationSetupId_SortOrder" ON "EvaluationDimensions" ("EvaluationSetupId", "SortOrder");""",
        """CREATE TABLE "EvaluationRecords" ("Id" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, "EvaluationSetupId" TEXT NOT NULL, "StudentId" TEXT NOT NULL, "TeachingTaskId" TEXT NOT NULL, "SubmittedAt" TEXT NULL, CONSTRAINT "PK_EvaluationRecords" PRIMARY KEY ("Id"), CONSTRAINT "FK_EvaluationRecords_EvaluationSetups_EvaluationSetupId" FOREIGN KEY ("EvaluationSetupId") REFERENCES "EvaluationSetups" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_EvaluationRecords_Students_StudentId" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_EvaluationRecords_TeachingTasks_TeachingTaskId" FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT);""",
        """CREATE UNIQUE INDEX "IX_EvaluationRecords_SetupId_StudentId_TaskId" ON "EvaluationRecords" ("EvaluationSetupId", "StudentId", "TeachingTaskId");""",
        """CREATE TABLE "EvaluationScores" ("EvaluationRecordId" TEXT NOT NULL, "EvaluationDimensionId" TEXT NOT NULL, "Score" INTEGER NOT NULL, CONSTRAINT "PK_EvaluationScores" PRIMARY KEY ("EvaluationRecordId", "EvaluationDimensionId"), CONSTRAINT "FK_EvaluationScores_EvaluationRecords_EvaluationRecordId" FOREIGN KEY ("EvaluationRecordId") REFERENCES "EvaluationRecords" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_EvaluationScores_EvaluationDimensions_EvaluationDimensionId" FOREIGN KEY ("EvaluationDimensionId") REFERENCES "EvaluationDimensions" ("Id") ON DELETE RESTRICT);""",
    ];

    private const string MakeupExamsMigration = "MakeupExams";

    private static readonly string[] MakeupExamStatements =
    [
        """CREATE TABLE "MakeupExamPlans" ("Id" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, "AcademicTermId" TEXT NOT NULL, "Name" TEXT NOT NULL, "Status" INTEGER NOT NULL, "Notes" TEXT NULL, "PublishedAt" TEXT NULL, CONSTRAINT "PK_MakeupExamPlans" PRIMARY KEY ("Id"), CONSTRAINT "FK_MakeupExamPlans_AcademicTerms_AcademicTermId" FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id") ON DELETE RESTRICT);""",
        """CREATE INDEX "IX_MakeupExamPlans_AcademicTermId_Status" ON "MakeupExamPlans" ("AcademicTermId", "Status");""",
        """CREATE TABLE "MakeupExamSessions" ("Id" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, "MakeupExamPlanId" TEXT NOT NULL, "TeachingTaskId" TEXT NOT NULL, "ClassroomId" TEXT NULL, "ExamDate" TEXT NOT NULL, "StartPeriod" INTEGER NOT NULL, "PeriodCount" INTEGER NOT NULL, "StartsAt" TEXT NOT NULL, "EndsAt" TEXT NOT NULL, "RequiredBuildingId" TEXT NULL, "RequiredBuildingIds" TEXT NULL, "RequiredInvigilatorCount" INTEGER NOT NULL, "Notes" TEXT NULL, CONSTRAINT "PK_MakeupExamSessions" PRIMARY KEY ("Id"), CONSTRAINT "FK_MakeupExamSessions_MakeupExamPlans_MakeupExamPlanId" FOREIGN KEY ("MakeupExamPlanId") REFERENCES "MakeupExamPlans" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_MakeupExamSessions_TeachingTasks_TeachingTaskId" FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_MakeupExamSessions_Classrooms_ClassroomId" FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id") ON DELETE SET NULL, CONSTRAINT "FK_MakeupExamSessions_Buildings_RequiredBuildingId" FOREIGN KEY ("RequiredBuildingId") REFERENCES "Buildings" ("Id") ON DELETE SET NULL);""",
        """CREATE INDEX "IX_MakeupExamSessions_MakeupExamPlanId_StartsAt" ON "MakeupExamSessions" ("MakeupExamPlanId", "StartsAt");""",
        """CREATE INDEX "IX_MakeupExamSessions_TeachingTaskId" ON "MakeupExamSessions" ("TeachingTaskId");""",
        """CREATE INDEX "IX_MakeupExamSessions_MakeupExamPlanId_ExamDate" ON "MakeupExamSessions" ("MakeupExamPlanId", "ExamDate");""",
        """CREATE INDEX "IX_MakeupExamSessions_RequiredBuildingId" ON "MakeupExamSessions" ("RequiredBuildingId");""",
        """CREATE TABLE "MakeupExamSessionInvigilators" ("MakeupExamSessionId" TEXT NOT NULL, "TeacherId" TEXT NOT NULL, CONSTRAINT "PK_MakeupExamSessionInvigilators" PRIMARY KEY ("MakeupExamSessionId", "TeacherId"), CONSTRAINT "FK_MakeupExamSessionInvigilators_MakeupExamSessions_MakeupExamSessionId" FOREIGN KEY ("MakeupExamSessionId") REFERENCES "MakeupExamSessions" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_MakeupExamSessionInvigilators_Teachers_TeacherId" FOREIGN KEY ("TeacherId") REFERENCES "Teachers" ("Id") ON DELETE RESTRICT);""",
        """CREATE TABLE "MakeupExamEnrollments" ("MakeupExamSessionId" TEXT NOT NULL, "StudentId" TEXT NOT NULL, "Reason" INTEGER NOT NULL, "SourceGradeRecordId" TEXT NULL, "SourceDeferredExamId" TEXT NULL, "MakeupScore" TEXT NULL, CONSTRAINT "PK_MakeupExamEnrollments" PRIMARY KEY ("MakeupExamSessionId", "StudentId"), CONSTRAINT "FK_MakeupExamEnrollments_MakeupExamSessions_MakeupExamSessionId" FOREIGN KEY ("MakeupExamSessionId") REFERENCES "MakeupExamSessions" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_MakeupExamEnrollments_Students_StudentId" FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT, CONSTRAINT "FK_MakeupExamEnrollments_GradeRecords_SourceGradeRecordId" FOREIGN KEY ("SourceGradeRecordId") REFERENCES "GradeRecords" ("Id") ON DELETE SET NULL, CONSTRAINT "FK_MakeupExamEnrollments_DeferredExams_SourceDeferredExamId" FOREIGN KEY ("SourceDeferredExamId") REFERENCES "DeferredExams" ("Id") ON DELETE SET NULL);""",
        """CREATE INDEX "IX_MakeupExamEnrollments_StudentId_MakeupExamSessionId" ON "MakeupExamEnrollments" ("StudentId", "MakeupExamSessionId");""",
    ];

    private const string MakeupExamAutoJobsMigration = "MakeupExamAutoJobs";

    private static readonly string[] MakeupExamAutoJobStatements =
    [
        """CREATE TABLE "MakeupExamAutoJobs" ("Id" TEXT NOT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, "MakeupExamPlanId" TEXT NOT NULL, "Status" INTEGER NOT NULL, "TotalCourses" INTEGER NOT NULL, "ProcessedCourses" INTEGER NOT NULL, "CreatedSessions" INTEGER NOT NULL, "EnrolledStudents" INTEGER NOT NULL, "MessagesJson" TEXT NULL, "ErrorMessage" TEXT NULL, "StartedAt" TEXT NULL, "CompletedAt" TEXT NULL, CONSTRAINT "PK_MakeupExamAutoJobs" PRIMARY KEY ("Id"), CONSTRAINT "FK_MakeupExamAutoJobs_MakeupExamPlans_MakeupExamPlanId" FOREIGN KEY ("MakeupExamPlanId") REFERENCES "MakeupExamPlans" ("Id") ON DELETE CASCADE);""",
        """CREATE INDEX "IX_MakeupExamAutoJobs_MakeupExamPlanId_CreatedAt" ON "MakeupExamAutoJobs" ("MakeupExamPlanId", "CreatedAt");""",
        """CREATE INDEX "IX_MakeupExamAutoJobs_Status_CreatedAt" ON "MakeupExamAutoJobs" ("Status", "CreatedAt");""",
    ];

    private const string ExamArrangementJobsMigration = "ExamArrangementJobs";

    private static readonly string[] ExamArrangementJobStatements =
    [
        """CREATE TABLE "ExamArrangementJobs" ("Id" TEXT NOT NULL, "Kind" INTEGER NOT NULL, "PlanId" TEXT NOT NULL, "ActivePlanId" TEXT NULL, "RequestedByUserId" TEXT NULL, "SessionIdsJson" TEXT NULL, "AssignClassrooms" INTEGER NOT NULL, "AssignInvigilators" INTEGER NOT NULL, "Status" INTEGER NOT NULL, "TotalSessions" INTEGER NOT NULL, "ProcessedSessions" INTEGER NOT NULL, "CurrentStep" TEXT NULL, "ResultMessage" TEXT NULL, "ErrorMessage" TEXT NULL, "StartedAt" TEXT NULL, "CompletedAt" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "PK_ExamArrangementJobs" PRIMARY KEY ("Id"));""",
        """CREATE INDEX "IX_ExamArrangementJobs_Kind_Plan_CreatedAt" ON "ExamArrangementJobs" ("Kind", "PlanId", "CreatedAt");""",
        """CREATE INDEX "IX_ExamArrangementJobs_RequestedByUserId" ON "ExamArrangementJobs" ("RequestedByUserId");""",
        """CREATE INDEX "IX_ExamArrangementJobs_Status_CreatedAt" ON "ExamArrangementJobs" ("Status", "CreatedAt");""",
        """CREATE UNIQUE INDEX "UX_ExamArrangementJobs_Kind_ActivePlan" ON "ExamArrangementJobs" ("Kind", "ActivePlanId");""",
    ];

    private const string ExamSignInExportJobsMigration = "ExamSignInExportJobs";

    private static readonly string[] ExamSignInExportJobStatements =
    [
        """CREATE TABLE "ExamSignInExportJobs" ("Id" TEXT NOT NULL, "PlanId" TEXT NOT NULL, "Status" INTEGER NOT NULL, "RequestedByUserId" TEXT NULL, "FileName" TEXT NULL, "FileBytes" BLOB NULL, "FileSize" INTEGER NOT NULL, "CurrentStep" TEXT NULL, "ErrorMessage" TEXT NULL, "StartedAt" TEXT NULL, "CompletedAt" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL, CONSTRAINT "PK_ExamSignInExportJobs" PRIMARY KEY ("Id"));""",
        """CREATE INDEX "IX_ExamSignInExportJobs_PlanId_CreatedAt" ON "ExamSignInExportJobs" ("PlanId", "CreatedAt");""",
        """CREATE INDEX "IX_ExamSignInExportJobs_Status_CreatedAt" ON "ExamSignInExportJobs" ("Status", "CreatedAt");""",
        """CREATE INDEX "IX_ExamSignInExportJobs_RequestedByUserId" ON "ExamSignInExportJobs" ("RequestedByUserId");""",
    ];

    private static readonly string[] UnifiedMessageCenterStatements =
    [
        """
        CREATE TABLE "MessageDispatches" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_MessageDispatches" PRIMARY KEY,
            "SenderUserId" TEXT NOT NULL,
            "SenderName" TEXT NOT NULL,
            "Title" TEXT NOT NULL,
            "Content" TEXT NOT NULL,
            "Category" INTEGER NOT NULL,
            "AudienceType" INTEGER NOT NULL,
            "AudienceId" TEXT NULL,
            "AudienceName" TEXT NOT NULL,
            "RecipientCount" INTEGER NOT NULL,
            "LinkUrl" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL
        );
        """,
        """CREATE INDEX "IX_MessageDispatches_SenderUserId_CreatedAt" ON "MessageDispatches" ("SenderUserId", "CreatedAt");""",
        """ALTER TABLE "Notifications" ADD COLUMN "Category" INTEGER NOT NULL DEFAULT 1;""",
        """ALTER TABLE "Notifications" ADD COLUMN "MessageDispatchId" TEXT NULL REFERENCES "MessageDispatches" ("Id") ON DELETE CASCADE;""",
        """CREATE INDEX "IX_Notifications_MessageDispatchId" ON "Notifications" ("MessageDispatchId");""",
        """CREATE INDEX "IX_Notifications_UserId_Category_CreatedAt" ON "Notifications" ("UserId", "Category", "CreatedAt");"""
    ];

    private static readonly string[] ClassroomReservationStatements =
    [
        """
        CREATE TABLE "ClassroomReservations" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ClassroomReservations" PRIMARY KEY,
            "ApplicantUserId" TEXT NOT NULL,
            "ApplicantName" TEXT NOT NULL,
            "ApplicantCollegeId" TEXT NOT NULL,
            "AcademicTermId" TEXT NOT NULL,
            "ClassroomId" TEXT NOT NULL,
            "ReservationDate" TEXT NOT NULL,
            "StartPeriod" INTEGER NOT NULL,
            "PeriodCount" INTEGER NOT NULL,
            "AttendeeCount" INTEGER NOT NULL,
            "Purpose" TEXT NOT NULL,
            "ContactPhone" TEXT NOT NULL,
            "Notes" TEXT NULL,
            "Status" INTEGER NOT NULL,
            "ReviewedByUserId" TEXT NULL,
            "ReviewedAt" TEXT NULL,
            "ReviewComment" TEXT NULL,
            "CancelledAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ClassroomReservations_AspNetUsers_ApplicantUserId"
                FOREIGN KEY ("ApplicantUserId") REFERENCES "AspNetUsers" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_ClassroomReservations_Colleges_ApplicantCollegeId"
                FOREIGN KEY ("ApplicantCollegeId") REFERENCES "Colleges" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_ClassroomReservations_AcademicTerms_AcademicTermId"
                FOREIGN KEY ("AcademicTermId") REFERENCES "AcademicTerms" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_ClassroomReservations_Classrooms_ClassroomId"
                FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_ClassroomReservations_AspNetUsers_ReviewedByUserId"
                FOREIGN KEY ("ReviewedByUserId") REFERENCES "AspNetUsers" ("Id")
                ON DELETE SET NULL
        );
        """,
        """
        CREATE INDEX "IX_ClassroomReservations_ApplicantUserId_Status_CreatedAt"
        ON "ClassroomReservations" ("ApplicantUserId", "Status", "CreatedAt");
        """,
        """
        CREATE INDEX "IX_ClassroomReservations_ApplicantCollegeId_Status_ReservationDate"
        ON "ClassroomReservations" (
            "ApplicantCollegeId",
            "Status",
            "ReservationDate"
        );
        """,
        """
        CREATE INDEX "IX_ClassroomReservations_ClassroomId_ReservationDate_Status_StartPeriod"
        ON "ClassroomReservations" (
            "ClassroomId",
            "ReservationDate",
            "Status",
            "StartPeriod"
        );
        """,
        """
        CREATE INDEX "IX_ClassroomReservations_AcademicTermId"
        ON "ClassroomReservations" ("AcademicTermId");
        """,
        """
        CREATE INDEX "IX_ClassroomReservations_ReviewedByUserId"
        ON "ClassroomReservations" ("ReviewedByUserId");
        """
    ];

    private static readonly string[] BackgroundJobOutboxStatements =
    [
        """
        CREATE TABLE "BackgroundJobOutboxMessages" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_BackgroundJobOutboxMessages" PRIMARY KEY,
            "JobKind" INTEGER NOT NULL,
            "JobId" TEXT NOT NULL,
            "State" INTEGER NOT NULL,
            "PublishAttempts" INTEGER NOT NULL,
            "ProcessingAttempts" INTEGER NOT NULL,
            "PublishedAt" TEXT NULL,
            "ProcessingToken" TEXT NULL,
            "LeaseExpiresAt" TEXT NULL,
            "CompletedAt" TEXT NULL,
            "LastError" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_BackgroundJobOutboxMessages_JobKind_JobId"
        ON "BackgroundJobOutboxMessages" ("JobKind", "JobId");
        """,
        """
        CREATE INDEX "IX_BackgroundJobOutboxMessages_LeaseExpiresAt"
        ON "BackgroundJobOutboxMessages" ("LeaseExpiresAt");
        """,
        """
        CREATE INDEX "IX_BackgroundJobOutboxMessages_State_CreatedAt"
        ON "BackgroundJobOutboxMessages" ("State", "CreatedAt");
        """,
        """
        CREATE INDEX "IX_BackgroundJobOutboxMessages_State_CompletedAt"
        ON "BackgroundJobOutboxMessages" ("State", "CompletedAt");
        """
    ];

    private static readonly string[] AcademicPlanningPrerequisiteStatements =
    [
        """
        CREATE TABLE "CoursePrerequisites" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CoursePrerequisites" PRIMARY KEY,
            "CourseId" TEXT NOT NULL,
            "PrerequisiteCourseId" TEXT NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_CoursePrerequisites_Courses_CourseId"
                FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_CoursePrerequisites_Courses_PrerequisiteCourseId"
                FOREIGN KEY ("PrerequisiteCourseId") REFERENCES "Courses" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_CoursePrerequisites_CourseId_PrerequisiteCourseId"
        ON "CoursePrerequisites" ("CourseId", "PrerequisiteCourseId");
        """,
        """
        CREATE INDEX "IX_CoursePrerequisites_PrerequisiteCourseId"
        ON "CoursePrerequisites" ("PrerequisiteCourseId");
        """
    ];

    private static readonly string[] ExamRoomMixingStatements =
    [
        """
        CREATE TABLE "ExamRooms" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExamRooms" PRIMARY KEY,
            "ExamPlanId" TEXT NOT NULL,
            "CourseId" TEXT NOT NULL,
            "ClassroomId" TEXT NOT NULL,
            "ExamDate" TEXT NOT NULL,
            "StartPeriod" INTEGER NOT NULL,
            "PeriodCount" INTEGER NOT NULL,
            "StartsAt" TEXT NOT NULL,
            "EndsAt" TEXT NOT NULL,
            "RequiredInvigilatorCount" INTEGER NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExamRooms_ExamPlans_ExamPlanId"
                FOREIGN KEY ("ExamPlanId") REFERENCES "ExamPlans" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_ExamRooms_Courses_CourseId"
                FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_ExamRooms_Classrooms_ClassroomId"
                FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX "IX_ExamRooms_Plan_Time"
        ON "ExamRooms" ("ExamPlanId", "StartsAt");
        """,
        """
        CREATE INDEX "IX_ExamRooms_Plan_Room_Time"
        ON "ExamRooms" ("ExamPlanId", "ClassroomId", "StartsAt");
        """,
        """
        CREATE INDEX "IX_ExamRooms_CourseId"
        ON "ExamRooms" ("CourseId");
        """,
        """
        CREATE INDEX "IX_ExamRooms_ClassroomId"
        ON "ExamRooms" ("ClassroomId");
        """,
        """
        CREATE TABLE "ExamRoomSessions" (
            "ExamRoomId" TEXT NOT NULL,
            "ExamSessionId" TEXT NOT NULL,
            CONSTRAINT "PK_ExamRoomSessions"
                PRIMARY KEY ("ExamRoomId", "ExamSessionId"),
            CONSTRAINT "FK_ExamRoomSessions_ExamRooms_ExamRoomId"
                FOREIGN KEY ("ExamRoomId") REFERENCES "ExamRooms" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_ExamRoomSessions_ExamSessions_ExamSessionId"
                FOREIGN KEY ("ExamSessionId") REFERENCES "ExamSessions" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX "IX_ExamRoomSessions_SessionId"
        ON "ExamRoomSessions" ("ExamSessionId");
        """,
        """
        CREATE TABLE "ExamSeats" (
            "ExamRoomId" TEXT NOT NULL,
            "ExamSessionId" TEXT NOT NULL,
            "StudentId" TEXT NOT NULL,
            "SeatNumber" INTEGER NOT NULL,
            CONSTRAINT "PK_ExamSeats"
                PRIMARY KEY ("ExamRoomId", "StudentId"),
            CONSTRAINT "FK_ExamSeats_ExamRooms_ExamRoomId"
                FOREIGN KEY ("ExamRoomId") REFERENCES "ExamRooms" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_ExamSeats_ExamSessions_ExamSessionId"
                FOREIGN KEY ("ExamSessionId") REFERENCES "ExamSessions" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_ExamSeats_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX "UX_ExamSeats_Session_Student"
        ON "ExamSeats" ("ExamSessionId", "StudentId");
        """,
        """
        CREATE INDEX "IX_ExamSeats_StudentId"
        ON "ExamSeats" ("StudentId");
        """,
        """
        CREATE TABLE "ExamRoomInvigilators" (
            "ExamRoomId" TEXT NOT NULL,
            "TeacherId" TEXT NOT NULL,
            CONSTRAINT "PK_ExamRoomInvigilators"
                PRIMARY KEY ("ExamRoomId", "TeacherId"),
            CONSTRAINT "FK_ExamRoomInvigilators_ExamRooms_ExamRoomId"
                FOREIGN KEY ("ExamRoomId") REFERENCES "ExamRooms" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_ExamRoomInvigilators_Teachers_TeacherId"
                FOREIGN KEY ("TeacherId") REFERENCES "Teachers" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX "IX_ExamRoomInvigilators_TeacherId"
        ON "ExamRoomInvigilators" ("TeacherId");
        """
    ];

    private static readonly string[] ExamPublishJobStatements =
    [
        """
        CREATE TABLE "ExamPublishJobs" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExamPublishJobs" PRIMARY KEY,
            "Kind" INTEGER NOT NULL,
            "PlanId" TEXT NOT NULL,
            "ActivePlanId" TEXT NULL,
            "RequestedByUserId" TEXT NULL,
            "Status" INTEGER NOT NULL,
            "CurrentStep" TEXT NULL,
            "ErrorMessage" TEXT NULL,
            "StartedAt" TEXT NULL,
            "CompletedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL
        );
        """
    ];

    private static readonly string[] ExperimentManagementStatements =
    [
        """
        CREATE TABLE "ExperimentProjects" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExperimentProjects" PRIMARY KEY,
            "TeachingTaskId" TEXT NOT NULL,
            "Code" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "ArrangementMode" INTEGER NOT NULL,
            "Description" TEXT NULL,
            "Requirements" TEXT NULL,
            "StartDate" TEXT NOT NULL,
            "EndDate" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "PublishedAt" TEXT NULL,
            "ClosedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExperimentProjects_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_ExperimentProjects_TeachingTaskId_Code"
        ON "ExperimentProjects" ("TeachingTaskId", "Code");
        """,
        """
        CREATE INDEX "IX_ExperimentProjects_Status_StartDate_EndDate"
        ON "ExperimentProjects" ("Status", "StartDate", "EndDate");
        """,
        """
        CREATE TABLE "ExperimentSessions" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExperimentSessions" PRIMARY KEY,
            "ExperimentProjectId" TEXT NOT NULL,
            "ClassroomId" TEXT NOT NULL,
            "SessionDate" TEXT NOT NULL,
            "StartPeriod" INTEGER NOT NULL,
            "PeriodCount" INTEGER NOT NULL,
            "Capacity" INTEGER NOT NULL,
            "ReservedCount" INTEGER NOT NULL,
            "Notes" TEXT NULL,
            "Status" INTEGER NOT NULL,
            "CancelledAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExperimentSessions_ExperimentProjects_ExperimentProjectId"
                FOREIGN KEY ("ExperimentProjectId")
                REFERENCES "ExperimentProjects" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_ExperimentSessions_Classrooms_ClassroomId"
                FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX "IX_ExperimentSessions_ExperimentProjectId_SessionDate_StartPeriod"
        ON "ExperimentSessions" (
            "ExperimentProjectId",
            "SessionDate",
            "StartPeriod"
        );
        """,
        """
        CREATE INDEX "IX_ExperimentSessions_ClassroomId_SessionDate_Status_StartPeriod"
        ON "ExperimentSessions" (
            "ClassroomId",
            "SessionDate",
            "Status",
            "StartPeriod"
        );
        """,
        """
        CREATE TABLE "ExperimentBookings" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExperimentBookings" PRIMARY KEY,
            "ExperimentProjectId" TEXT NOT NULL,
            "ExperimentSessionId" TEXT NOT NULL,
            "StudentId" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "BookedAt" TEXT NOT NULL,
            "CancelledAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExperimentBookings_ExperimentProjects_ExperimentProjectId"
                FOREIGN KEY ("ExperimentProjectId")
                REFERENCES "ExperimentProjects" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_ExperimentBookings_ExperimentSessions_ExperimentSessionId"
                FOREIGN KEY ("ExperimentSessionId")
                REFERENCES "ExperimentSessions" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_ExperimentBookings_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_ExperimentBookings_ExperimentProjectId_StudentId"
        ON "ExperimentBookings" ("ExperimentProjectId", "StudentId");
        """,
        """
        CREATE INDEX "IX_ExperimentBookings_ExperimentSessionId_Status_BookedAt"
        ON "ExperimentBookings" (
            "ExperimentSessionId",
            "Status",
            "BookedAt"
        );
        """
    ];

    private static readonly string[] ExperimentGradeItemSourceStatements =
    [
        """
        ALTER TABLE "GradeItems"
        ADD "SourceType" INTEGER NOT NULL DEFAULT 1;
        """,
        """
        ALTER TABLE "GradeItems"
        ADD "SourceSnapshotAt" TEXT NULL;
        """
    ];

    private static readonly string[] ExperimentGradeManagementStatements =
    [
        """
        CREATE TABLE "ExperimentGradeSheets" (
            "Id" TEXT NOT NULL
                CONSTRAINT "PK_ExperimentGradeSheets" PRIMARY KEY,
            "ExperimentProjectId" TEXT NOT NULL,
            "ContributionWeight" TEXT NOT NULL,
            "PassScore" TEXT NOT NULL,
            "Status" INTEGER NOT NULL,
            "ReviewComment" TEXT NULL,
            "SubmittedAt" TEXT NULL,
            "ReviewedAt" TEXT NULL,
            "PublishedAt" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExperimentGradeSheets_ExperimentProjects_ExperimentProjectId"
                FOREIGN KEY ("ExperimentProjectId")
                REFERENCES "ExperimentProjects" ("Id")
                ON DELETE CASCADE
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_ExperimentGradeSheets_ExperimentProjectId"
        ON "ExperimentGradeSheets" ("ExperimentProjectId");
        """,
        """
        CREATE TABLE "ExperimentGradeItems" (
            "Id" TEXT NOT NULL
                CONSTRAINT "PK_ExperimentGradeItems" PRIMARY KEY,
            "ExperimentGradeSheetId" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "Kind" INTEGER NOT NULL,
            "Weight" TEXT NOT NULL,
            "SortOrder" INTEGER NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExperimentGradeItems_ExperimentGradeSheets_ExperimentGradeSheetId"
                FOREIGN KEY ("ExperimentGradeSheetId")
                REFERENCES "ExperimentGradeSheets" ("Id")
                ON DELETE CASCADE
        );
        """,
        """
        CREATE INDEX "IX_ExperimentGradeItems_ExperimentGradeSheetId_SortOrder"
        ON "ExperimentGradeItems" ("ExperimentGradeSheetId", "SortOrder");
        """,
        """
        CREATE TABLE "ExperimentGradeRecords" (
            "Id" TEXT NOT NULL
                CONSTRAINT "PK_ExperimentGradeRecords" PRIMARY KEY,
            "ExperimentGradeSheetId" TEXT NOT NULL,
            "StudentId" TEXT NOT NULL,
            "ExperimentSessionId" TEXT NULL,
            "ParticipationStatus" INTEGER NOT NULL,
            "TotalScore" TEXT NULL,
            "IsPassed" INTEGER NULL,
            "SafetyViolation" INTEGER NOT NULL,
            "AttemptNumber" INTEGER NOT NULL,
            "SubmissionReference" TEXT NULL,
            "SubmittedAt" TEXT NULL,
            "IsLate" INTEGER NOT NULL,
            "TeacherComment" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExperimentGradeRecords_ExperimentGradeSheets_ExperimentGradeSheetId"
                FOREIGN KEY ("ExperimentGradeSheetId")
                REFERENCES "ExperimentGradeSheets" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_ExperimentGradeRecords_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id")
                ON DELETE RESTRICT,
            CONSTRAINT "FK_ExperimentGradeRecords_ExperimentSessions_ExperimentSessionId"
                FOREIGN KEY ("ExperimentSessionId")
                REFERENCES "ExperimentSessions" ("Id")
                ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_ExperimentGradeRecords_ExperimentGradeSheetId_StudentId"
        ON "ExperimentGradeRecords" ("ExperimentGradeSheetId", "StudentId");
        """,
        """
        CREATE INDEX "IX_ExperimentGradeRecords_StudentId"
        ON "ExperimentGradeRecords" ("StudentId");
        """,
        """
        CREATE INDEX "IX_ExperimentGradeRecords_ExperimentSessionId"
        ON "ExperimentGradeRecords" ("ExperimentSessionId");
        """,
        """
        CREATE TABLE "ExperimentGradeItemScores" (
            "ExperimentGradeRecordId" TEXT NOT NULL,
            "ExperimentGradeItemId" TEXT NOT NULL,
            "Score" TEXT NULL,
            "Comment" TEXT NULL,
            CONSTRAINT "PK_ExperimentGradeItemScores"
                PRIMARY KEY (
                    "ExperimentGradeRecordId",
                    "ExperimentGradeItemId"
                ),
            CONSTRAINT "FK_ExperimentGradeItemScores_ExperimentGradeRecords_ExperimentGradeRecordId"
                FOREIGN KEY ("ExperimentGradeRecordId")
                REFERENCES "ExperimentGradeRecords" ("Id")
                ON DELETE CASCADE,
            CONSTRAINT "FK_ExperimentGradeItemScores_ExperimentGradeItems_ExperimentGradeItemId"
                FOREIGN KEY ("ExperimentGradeItemId")
                REFERENCES "ExperimentGradeItems" ("Id")
                ON DELETE CASCADE
        );
        """,
        """
        CREATE INDEX "IX_ExperimentGradeItemScores_ExperimentGradeItemId"
        ON "ExperimentGradeItemScores" ("ExperimentGradeItemId");
        """
    ];

    private static readonly string[] IntegratedExperimentSchedulingStatements =
    [
        """
        ALTER TABLE "ScheduleEntries"
        ADD COLUMN "Kind" INTEGER NOT NULL DEFAULT 1;
        """
    ];

    private static readonly string[] SwaggerDocumentationSettingStatements =
    [
        """
        CREATE TABLE "SystemFeatureSettings" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_SystemFeatureSettings" PRIMARY KEY,
            "Key" TEXT NOT NULL,
            "IsEnabled" INTEGER NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_SystemFeatureSettings_Key"
        ON "SystemFeatureSettings" ("Key");
        """
    ];

    private static readonly string[] CourseGradeStatisticsRefreshSettingsStatements =
    [
        """CREATE TABLE IF NOT EXISTS "CourseGradeStatisticsRefreshSettings" ("Id" TEXT NOT NULL CONSTRAINT "PK_CourseGradeStatisticsRefreshSettings" PRIMARY KEY, "Key" TEXT NOT NULL, "IsEnabled" INTEGER NOT NULL, "IntervalSeconds" INTEGER NOT NULL, "BatchSize" INTEGER NOT NULL, "LastRunAt" TEXT NULL, "CreatedAt" TEXT NOT NULL, "UpdatedAt" TEXT NOT NULL);""",
        """CREATE UNIQUE INDEX IF NOT EXISTS "IX_CourseGradeStatisticsRefreshSettings_Key" ON "CourseGradeStatisticsRefreshSettings" ("Key");"""
    ];

    private static readonly string[] NotificationInboxIndexesStatements =
    [
        """DROP INDEX IF EXISTS "IX_Notifications_UserId_IsRead";""",
        """DROP INDEX IF EXISTS "IX_Notifications_UserId_Category_CreatedAt";""",
        """CREATE INDEX IF NOT EXISTS "IX_Notifications_UserId_CreatedAt_Id" ON "Notifications" ("UserId", "CreatedAt", "Id");""",
        """CREATE INDEX IF NOT EXISTS "IX_Notifications_UserId_IsRead_CreatedAt_Id" ON "Notifications" ("UserId", "IsRead", "CreatedAt", "Id");""",
        """CREATE INDEX IF NOT EXISTS "IX_Notifications_UserId_Category_CreatedAt_Id" ON "Notifications" ("UserId", "Category", "CreatedAt", "Id");"""
    ];

    private static readonly string[] ExperimentCourseGradesStatements =
    [
        """
        CREATE TABLE "ExperimentCourseGrades" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExperimentCourseGrades" PRIMARY KEY,
            "TeachingTaskId" TEXT NOT NULL,
            "StudentId" TEXT NOT NULL,
            "WeightedAverageScore" TEXT NULL,
            "TotalWeight" TEXT NOT NULL,
            "PublishedProjectCount" INTEGER NOT NULL,
            "RefreshedAt" TEXT NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExperimentCourseGrades_TeachingTasks_TeachingTaskId"
                FOREIGN KEY ("TeachingTaskId") REFERENCES "TeachingTasks" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_ExperimentCourseGrades_Students_StudentId"
                FOREIGN KEY ("StudentId") REFERENCES "Students" ("Id") ON DELETE RESTRICT
        );
        """,
        """CREATE INDEX "IX_ExperimentCourseGrades_StudentId" ON "ExperimentCourseGrades" ("StudentId");""",
        """CREATE UNIQUE INDEX "IX_ExperimentCourseGrades_TeachingTaskId_StudentId" ON "ExperimentCourseGrades" ("TeachingTaskId", "StudentId");""",
        """
        INSERT INTO "ExperimentCourseGrades"
            ("Id", "TeachingTaskId", "StudentId", "WeightedAverageScore",
             "TotalWeight", "PublishedProjectCount", "RefreshedAt",
             "CreatedAt", "UpdatedAt")
        SELECT
            lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-' ||
            '4' || substr(lower(hex(randomblob(2))), 2) || '-' ||
            substr('89ab', abs(random()) % 4 + 1, 1) ||
            substr(lower(hex(randomblob(2))), 2) || '-' || lower(hex(randomblob(6))),
            project."TeachingTaskId",
            record."StudentId",
            CASE
                WHEN COUNT(*) = (
                    SELECT COUNT(*)
                    FROM "ExperimentGradeSheets" AS all_sheet
                    INNER JOIN "ExperimentProjects" AS all_project
                        ON all_project."Id" = all_sheet."ExperimentProjectId"
                    WHERE all_sheet."Status" = 4
                      AND all_project."TeachingTaskId" = project."TeachingTaskId")
                 AND SUM(CASE WHEN record."TotalScore" IS NULL THEN 1 ELSE 0 END) = 0
                THEN ROUND(
                    SUM(record."TotalScore" * sheet."ContributionWeight") /
                    SUM(sheet."ContributionWeight"), 1)
                ELSE NULL
            END,
            (
                SELECT COALESCE(SUM(all_sheet."ContributionWeight"), 0)
                FROM "ExperimentGradeSheets" AS all_sheet
                INNER JOIN "ExperimentProjects" AS all_project
                    ON all_project."Id" = all_sheet."ExperimentProjectId"
                WHERE all_sheet."Status" = 4
                  AND all_project."TeachingTaskId" = project."TeachingTaskId"),
            (
                SELECT COUNT(*)
                FROM "ExperimentGradeSheets" AS all_sheet
                INNER JOIN "ExperimentProjects" AS all_project
                    ON all_project."Id" = all_sheet."ExperimentProjectId"
                WHERE all_sheet."Status" = 4
                  AND all_project."TeachingTaskId" = project."TeachingTaskId"),
            strftime('%Y-%m-%d %H:%M:%f', 'now'),
            strftime('%Y-%m-%d %H:%M:%f', 'now'),
            strftime('%Y-%m-%d %H:%M:%f', 'now')
        FROM "ExperimentGradeRecords" AS record
        INNER JOIN "ExperimentGradeSheets" AS sheet
            ON sheet."Id" = record."ExperimentGradeSheetId"
        INNER JOIN "ExperimentProjects" AS project
            ON project."Id" = sheet."ExperimentProjectId"
        WHERE sheet."Status" = 4
        GROUP BY project."TeachingTaskId", record."StudentId";
        """
    ];

    private static readonly string[] ExperimentClassroomConstraintStatements =
    [
        """
        CREATE TABLE "TeachingTaskAllowedExperimentClassrooms" (
            "TeachingTaskScheduleConstraintId" TEXT NOT NULL,
            "ClassroomId" TEXT NOT NULL,
            CONSTRAINT "PK_TeachingTaskAllowedExperimentClassrooms"
                PRIMARY KEY ("TeachingTaskScheduleConstraintId", "ClassroomId"),
            CONSTRAINT "FK_TeachingTaskAllowedExperimentClassrooms_Constraints"
                FOREIGN KEY ("TeachingTaskScheduleConstraintId")
                REFERENCES "TeachingTaskScheduleConstraints" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_TeachingTaskAllowedExperimentClassrooms_Classrooms"
                FOREIGN KEY ("ClassroomId") REFERENCES "Classrooms" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE INDEX "IX_TeachingTaskAllowedExperimentClassrooms_ClassroomId"
        ON "TeachingTaskAllowedExperimentClassrooms" ("ClassroomId");
        """
    ];

    private static readonly string[] SeparateExperimentClassroomScopeStatements =
    [
        """
        ALTER TABLE "TeachingTaskScheduleConstraints"
        ADD COLUMN "ExperimentRequiredCampusId" TEXT NULL;
        """,
        """
        ALTER TABLE "TeachingTaskScheduleConstraints"
        ADD COLUMN "ExperimentRequiredBuildingId" TEXT NULL;
        """,
        """
        CREATE INDEX "IX_TeachingTaskScheduleConstraints_ExperimentRequiredCampusId"
        ON "TeachingTaskScheduleConstraints" ("ExperimentRequiredCampusId");
        """,
        """
        CREATE INDEX "IX_TeachingTaskScheduleConstraints_ExperimentRequiredBuildingId"
        ON "TeachingTaskScheduleConstraints" ("ExperimentRequiredBuildingId");
        """
    ];

    private static readonly string[] SelfScheduledExperimentSelectionStatements =
    [
        "ALTER TABLE \"ExperimentProjects\" ADD COLUMN \"SelectionStartsAt\" TEXT NULL;",
        "ALTER TABLE \"ExperimentProjects\" ADD COLUMN \"SelectionEndsAt\" TEXT NULL;",
        """
        CREATE TABLE "ExperimentSessionInstructors" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_ExperimentSessionInstructors" PRIMARY KEY,
            "ExperimentSessionId" TEXT NOT NULL,
            "TeacherId" TEXT NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_ExperimentSessionInstructors_ExperimentSessions_ExperimentSessionId"
                FOREIGN KEY ("ExperimentSessionId") REFERENCES "ExperimentSessions" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_ExperimentSessionInstructors_Teachers_TeacherId"
                FOREIGN KEY ("TeacherId") REFERENCES "Teachers" ("Id") ON DELETE RESTRICT
        );
        """,
        "CREATE UNIQUE INDEX \"IX_ExperimentSessionInstructors_ExperimentSessionId_TeacherId\" ON \"ExperimentSessionInstructors\" (\"ExperimentSessionId\", \"TeacherId\");",
        "CREATE INDEX \"IX_ExperimentSessionInstructors_TeacherId\" ON \"ExperimentSessionInstructors\" (\"TeacherId\");"
    ];

    private static readonly string[] ReusableCourseGroupsStatements =
    [
        """
        CREATE TABLE "CourseGroups" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CourseGroups" PRIMARY KEY,
            "Code" TEXT NOT NULL,
            "Name" TEXT NOT NULL,
            "Description" TEXT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_CourseGroups_Code" ON "CourseGroups" ("Code");
        """,
        """
        CREATE TABLE "CourseGroupCourses" (
            "Id" TEXT NOT NULL CONSTRAINT "PK_CourseGroupCourses" PRIMARY KEY,
            "CourseGroupId" TEXT NOT NULL,
            "CourseId" TEXT NOT NULL,
            "CreatedAt" TEXT NOT NULL,
            "UpdatedAt" TEXT NOT NULL,
            CONSTRAINT "FK_CourseGroupCourses_CourseGroups_CourseGroupId"
                FOREIGN KEY ("CourseGroupId") REFERENCES "CourseGroups" ("Id") ON DELETE CASCADE,
            CONSTRAINT "FK_CourseGroupCourses_Courses_CourseId"
                FOREIGN KEY ("CourseId") REFERENCES "Courses" ("Id") ON DELETE RESTRICT
        );
        """,
        """
        CREATE UNIQUE INDEX "IX_CourseGroupCourses_CourseGroupId_CourseId"
        ON "CourseGroupCourses" ("CourseGroupId", "CourseId");
        """,
        """
        CREATE INDEX "IX_CourseGroupCourses_CourseId" ON "CourseGroupCourses" ("CourseId");
        """
    ];
}
