<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        App\Support\SqliteCompat::statement(<<<'SQL'
CREATE TABLE `exam_drafts` (
`id` int UNSIGNED NOT NULL,
  `teacher_id` int NOT NULL,
  `class_section_id` int NOT NULL,
  `semester` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `school_year` varchar(9) COLLATE utf8mb4_unicode_ci NOT NULL,
  `exam_type` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `draft_title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `description` text COLLATE utf8mb4_unicode_ci,
  `teacher_file` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `teacher_filename` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `status` enum('draft','submitted','reviewed','finalized','rejected') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'draft',
  `admin_id` int DEFAULT NULL,
  `admin_comments` text COLLATE utf8mb4_unicode_ci,
  `reviewed_at` datetime DEFAULT NULL,
  `final_file` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `final_filename` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `version` smallint UNSIGNED NOT NULL DEFAULT '1',
  `previous_draft_id` int UNSIGNED DEFAULT NULL,
  `is_legacy` tinyint(1) NOT NULL DEFAULT '0',
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SQL
        );

        App\Support\SqliteCompat::statement(<<<'SQL'
ALTER TABLE `exam_drafts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_exam_drafts_teacher` (`teacher_id`),
  ADD KEY `idx_exam_drafts_class_section` (`class_section_id`),
  ADD KEY `idx_exam_drafts_status` (`status`),
  ADD KEY `idx_exam_drafts_prev` (`previous_draft_id`);
SQL
        );

        App\Support\SqliteCompat::statement(<<<'SQL'
ALTER TABLE `exam_drafts`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
SQL
        );

        App\Support\SqliteCompat::statement(<<<'SQL'
ALTER TABLE `exam_drafts`
  ADD CONSTRAINT `fk_exam_drafts_previous` FOREIGN KEY (`previous_draft_id`) REFERENCES `exam_drafts` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
SQL
        );

    }

    public function down(): void
    {
        Schema::dropIfExists('exam_drafts');
    }
};