<?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
    {
        // MySQL环境：禁用外键检查
        if (DB::getDriverName() !== 'sqlite') {
            DB::statement('SET FOREIGN_KEY_CHECKS=0');
        }

        $users = [];
        if (Schema::hasTable('users')) {
            // 备份现有数据（必须在删除表之前）
            $users = DB::table('users')->get();
            // 删除表并重新创建
            Schema::dropIfExists('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');
        });

        // 恢复数据（转换为自增id）
        foreach ($users as $user) {
            DB::table('users')->insert([
                'user_id' => $user->user_id, // 保留原始ID
                'username' => $user->username,
                'email' => $user->email,
                'password_hash' => $user->password_hash,
                'full_name' => $user->full_name,
                'role' => $user->role,
                'phone' => $user->phone,
                'department' => $user->department,
                'is_active' => $user->is_active,
                'created_at' => $user->created_at,
                'updated_at' => $user->updated_at,
                'last_login' => $user->last_login,
                'login_count' => $user->login_count,
                'deleted_at' => $user->deleted_at,
            ]);
        }

        // SQLite不支持SET FOREIGN_KEY_CHECKS，跳过这一步
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // 备份现有数据
        $users = DB::table('users')->get();

        // SQLite不支持SET FOREIGN_KEY_CHECKS，跳过这一步

        // 恢复原始表结构
        Schema::dropIfExists('users');

        Schema::create('users', function (Blueprint $table) {
            $table->string('user_id')->primary();
            $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');
        });

        // 恢复数据
        foreach ($users as $user) {
            DB::table('users')->insert([
                'user_id' => $user->user_id,
                'username' => $user->username,
                'email' => $user->email,
                'password_hash' => $user->password_hash,
                'full_name' => $user->full_name,
                'role' => $user->role,
                'phone' => $user->phone,
                'department' => $user->department,
                'is_active' => $user->is_active,
                'created_at' => $user->created_at,
                'updated_at' => $user->updated_at,
                'last_login' => $user->last_login,
                'login_count' => $user->login_count,
                'deleted_at' => $user->deleted_at,
            ]);
        }

        // SQLite不支持SET FOREIGN_KEY_CHECKS，跳过这一步
    }
};
