<?php

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

/**
 * 创建系统核心表
 *
 * 背景：系统核心表（admin_menu_terminals、admin_menus 等）由 install.sql 创建，
 * 不在迁移文件中。但后续迁移（如 2026_05_28_000002_add_user_terminal.php）
 * 会查询这些表，导致测试环境（使用 RefreshDatabase + migrate:fresh）下迁移失败。
 *
 * 此迁移在表不存在时创建（幂等），生产环境（install.sql 已创建表）会跳过。
 * 表结构与 install.sql 保持一致。
 */
return new class extends Migration
{
    public function up(): void
    {
        // 前台用户表（不含 remember_token，由 2026_06_16_000001 迁移添加）
        if (!Schema::hasTable('users')) {
            Schema::create('users', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('username', 50)->default('')->unique();
                $table->string('email', 100)->nullable()->unique();
                $table->string('phone', 20)->nullable();
                $table->string('password', 255)->default('');
                $table->string('nickname', 50)->nullable();
                $table->string('avatar', 255)->nullable();
                $table->unsignedTinyInteger('gender')->default(0)->comment('0-未知 1-男 2-女');
                $table->date('birthday')->nullable();
                $table->string('signature', 255)->nullable();
                $table->unsignedBigInteger('group_id')->nullable()->comment('关联user_groups表');
                $table->unsignedTinyInteger('status')->default(1)->comment('0-禁用 1-启用');
                $table->timestamp('email_verified_at')->nullable();
                $table->timestamp('phone_verified_at')->nullable();
                $table->timestamp('last_login_at')->nullable();
                $table->string('last_login_ip', 45)->nullable();
                $table->unsignedInteger('login_count')->default(0);
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->index('status');
                $table->index('group_id');
            });
        }

        // 后台管理员表
        if (!Schema::hasTable('admin_users')) {
            Schema::create('admin_users', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('username', 50)->unique();
                $table->string('password', 255);
                $table->string('name', 50)->nullable();
                $table->string('email', 100)->nullable();
                $table->string('phone', 20)->nullable();
                $table->string('avatar', 255)->nullable();
                $table->unsignedTinyInteger('status')->default(1)->comment('0-禁用 1-启用');
                $table->timestamp('last_login_at')->nullable();
                $table->string('last_login_ip', 45)->nullable();
                $table->unsignedInteger('login_count')->default(0);
                $table->timestamp('password_changed_at')->nullable();
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
            });
        }

        // 后台角色表
        if (!Schema::hasTable('admin_roles')) {
            Schema::create('admin_roles', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('name', 50);
                $table->string('code', 50)->unique();
                $table->string('description', 255)->nullable();
                $table->unsignedBigInteger('parent_id')->nullable();
                $table->unsignedInteger('sort')->default(0);
                $table->unsignedTinyInteger('status')->default(1);
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->index('parent_id');
                $table->index('status');
            });
        }

        // 管理员-角色关联表
        if (!Schema::hasTable('admin_user_roles')) {
            Schema::create('admin_user_roles', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->unsignedBigInteger('user_id');
                $table->unsignedBigInteger('role_id');
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->unique(['user_id', 'role_id']);
                $table->index('role_id');
            });
        }

        // 角色-权限关联表
        if (!Schema::hasTable('admin_role_permissions')) {
            Schema::create('admin_role_permissions', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->unsignedBigInteger('role_id');
                $table->unsignedBigInteger('permission_id');
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->unique(['role_id', 'permission_id']);
                $table->index('permission_id');
            });
        }

        // 操作日志表
        if (!Schema::hasTable('admin_operation_logs')) {
            Schema::create('admin_operation_logs', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->unsignedBigInteger('user_id')->nullable();
                $table->string('module', 50)->nullable();
                $table->string('action', 50)->nullable();
                $table->string('method', 10)->nullable();
                $table->string('path', 500)->nullable();
                $table->text('params')->nullable();
                $table->string('ip', 45)->nullable();
                $table->string('user_agent', 500)->nullable();
                $table->unsignedTinyInteger('status')->default(1);
                $table->text('error_message')->nullable();
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->index('user_id');
                $table->index('create_time');
            });
        }

        // 前台用户组表
        if (!Schema::hasTable('user_groups')) {
            Schema::create('user_groups', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('name', 50);
                $table->string('code', 50)->unique();
                $table->string('description', 255)->nullable();
                $table->string('icon', 50)->nullable();
                $table->string('color', 20)->nullable();
                $table->unsignedTinyInteger('is_default')->default(0);
                $table->unsignedInteger('sort')->default(0);
                $table->unsignedTinyInteger('status')->default(1);
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
            });
        }

        // 菜单终端类型表
        if (!Schema::hasTable('admin_menu_terminals')) {
            Schema::create('admin_menu_terminals', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('type', 20)->unique();
                $table->string('name', 50);
                $table->string('description', 255)->nullable();
                $table->unsignedInteger('sort')->default(0);
                $table->unsignedTinyInteger('status')->default(1);
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
            });
        }

        // 后台菜单表
        if (!Schema::hasTable('admin_menus')) {
            Schema::create('admin_menus', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->unsignedBigInteger('parent_id')->default(0);
                $table->string('name', 50);
                $table->string('icon', 100)->nullable();
                $table->string('path', 255)->nullable();
                $table->string('component', 255)->nullable();
                $table->string('permission_code', 100)->nullable();
                $table->unsignedTinyInteger('type')->default(2)->comment('1-目录 2-菜单 3-按钮');
                $table->unsignedTinyInteger('visible')->default(1);
                $table->unsignedInteger('sort')->default(0);
                $table->unsignedTinyInteger('status')->default(1);
                $table->string('terminal_type', 20)->default('admin');
                $table->string('app_id', 50)->nullable()->comment('NULL表示系统菜单');
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->index('parent_id');
                $table->index('terminal_type');
                $table->index('app_id');
            });
        }

        // 角色-菜单关联表
        if (!Schema::hasTable('admin_role_menus')) {
            Schema::create('admin_role_menus', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->unsignedBigInteger('role_id');
                $table->unsignedBigInteger('menu_id');
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->unique(['role_id', 'menu_id']);
                $table->index('menu_id');
            });
        }

        // 后台权限表
        if (!Schema::hasTable('admin_permissions')) {
            Schema::create('admin_permissions', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('name', 100);
                $table->string('code', 100)->unique();
                $table->string('module', 50)->nullable();
                $table->string('app_id', 50)->nullable()->comment('NULL表示系统权限');
                $table->unsignedTinyInteger('status')->default(1);
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->index('module');
                $table->index('app_id');
            });
        }

        // 配置组表
        if (!Schema::hasTable('config_groups')) {
            Schema::create('config_groups', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('name', 50);
                $table->string('code', 50)->unique();
                $table->string('app_id', 50)->nullable()->comment('NULL表示系统配置组');
                $table->unsignedInteger('sort')->default(0);
                $table->unsignedTinyInteger('status')->default(1);
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
            });
        }

        // 配置项表
        if (!Schema::hasTable('config_items')) {
            Schema::create('config_items', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->unsignedBigInteger('group_id');
                $table->string('name', 100);
                $table->string('code', 150);
                $table->text('value')->nullable();
                $table->string('type', 20)->default('text');
                $table->json('options')->nullable();
                $table->string('tips', 255)->nullable();
                $table->unsignedInteger('sort')->default(0);
                $table->unsignedTinyInteger('status')->default(1);
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->unique(['group_id', 'code']);
                $table->index('group_id');
            });
        }

        // 应用表
        if (!Schema::hasTable('apps')) {
            Schema::create('apps', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('app_id', 50)->unique();
                $table->string('name', 100);
                $table->string('description', 255)->nullable();
                $table->string('version', 20)->default('1.0.0');
                $table->string('author', 100)->nullable();
                $table->string('icon', 255)->nullable();
                $table->string('path', 255)->nullable();
                $table->unsignedTinyInteger('status')->default(0)->comment('0-已安装 1-已启用 2-已禁用');
                $table->unsignedTinyInteger('is_system')->default(0);
                $table->json('manifest')->nullable();
                $table->timestamp('install_time')->nullable();
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->index('status');
            });
        }

        // 应用依赖关系表
        if (!Schema::hasTable('app_dependencies')) {
            Schema::create('app_dependencies', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('app_id', 50);
                $table->string('depend_app_id', 50);
                $table->string('depend_version', 20)->nullable();
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->unique(['app_id', 'depend_app_id']);
                $table->index('depend_app_id');
            });
        }

        // 应用操作日志表
        if (!Schema::hasTable('app_operation_logs')) {
            Schema::create('app_operation_logs', function (Blueprint $table) {
                $table->unsignedBigInteger('id', true);
                $table->string('app_id', 50);
                $table->string('operation', 20)->comment('install/uninstall/enable/disable/upgrade');
                $table->string('version_from', 20)->nullable();
                $table->string('version_to', 20)->nullable();
                $table->unsignedBigInteger('operator_id')->nullable();
                $table->unsignedTinyInteger('result')->default(0)->comment('success/failed');
                $table->text('error_message')->nullable();
                $table->json('detail')->nullable();
                $table->timestamp('create_time')->nullable();
                $table->timestamp('update_time')->nullable();
                $table->index('app_id');
                $table->index('create_time');
            });
        }
    }

    public function down(): void
    {
        // 不删除系统核心表，避免影响生产环境
        // 这些表由 install.sql 创建，不应由迁移删除
    }
};
