<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 禁用外键检查
        if (DB::getDriverName() !== 'sqlite') {
            DB::statement('SET FOREIGN_KEY_CHECKS=0');
        }

        if (!Schema::hasTable('users')) {
            Schema::create('users', function (Blueprint $table) {
                $table->id(); // 自增主键
                $table->string('user_id')->nullable(); // 保留原始ID字段但可为空
                $table->string('username')->unique();
                $table->string('email')->unique()->nullable();
                $table->string('password_hash');
                $table->string('full_name');
                $table->enum('role', ['admin', 'teacher', 'student'])->default('teacher');
                $table->string('phone')->nullable();
                $table->string('department')->nullable();
                $table->boolean('is_active')->default(true);
                $table->timestamps();
                $table->datetime('last_login')->nullable();
                $table->integer('login_count')->default(0);
                $table->softDeletes();

                // 索引
                $table->index('role');
                $table->index('is_active');
                $table->index('phone');
                $table->index('email');
            });
        }

        // 恢复外键检查
        if (DB::getDriverName() !== 'sqlite') {
            DB::statement('SET FOREIGN_KEY_CHECKS=1');
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // 禁用外键检查
        if (DB::getDriverName() !== 'sqlite') {
            DB::statement('SET FOREIGN_KEY_CHECKS=0');
        }

        Schema::dropIfExists('users');

        // 恢复外键检查
        if (DB::getDriverName() !== 'sqlite') {
            DB::statement('SET FOREIGN_KEY_CHECKS=1');
        }
    }
};
