<?php

namespace Database\Seeders;

use App\Models\Permission;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $admin = User::query()->firstOrCreate(
            ['email' => 'admin@example.com'],
            [
                'name' => '系统管理员',
                'role' => 'admin',
                'is_active' => true,
                'password' => Hash::make('123456'),
            ],
        );

        $permissions = [
            ['code' => 'dashboard', 'name' => '控制台', 'type' => 'menu', 'menu_path' => '/admin/dashboard', 'sort' => 10],
            ['code' => 'users', 'name' => '用户管理', 'type' => 'menu', 'menu_path' => '/admin/users', 'sort' => 20],
            ['code' => 'users.create', 'name' => '新增用户', 'type' => 'button', 'parent_code' => 'users'],
            ['code' => 'users.update', 'name' => '编辑用户', 'type' => 'button', 'parent_code' => 'users'],
            ['code' => 'users.disable', 'name' => '禁用用户', 'type' => 'button', 'parent_code' => 'users'],
            ['code' => 'permissions', 'name' => '权限管理', 'type' => 'menu', 'menu_path' => '/admin/permissions', 'sort' => 30],
            ['code' => 'classes', 'name' => '班级管理', 'type' => 'menu', 'menu_path' => '/admin/classes', 'sort' => 40],
            ['code' => 'banks', 'name' => '题库管理', 'type' => 'menu', 'menu_path' => '/admin/banks', 'sort' => 50],
            ['code' => 'banks.create', 'name' => '新增题库', 'type' => 'button', 'parent_code' => 'banks'],
            ['code' => 'banks.update', 'name' => '编辑题库', 'type' => 'button', 'parent_code' => 'banks'],
            ['code' => 'banks.delete', 'name' => '删除题库', 'type' => 'button', 'parent_code' => 'banks'],
            ['code' => 'banks.share', 'name' => '题库授权', 'type' => 'button', 'parent_code' => 'banks'],
            ['code' => 'questions', 'name' => '题目管理', 'type' => 'menu', 'menu_path' => '/admin/questions', 'sort' => 60],
            ['code' => 'questions.import', 'name' => '批量导入', 'type' => 'button', 'parent_code' => 'questions'],
            ['code' => 'questions.export', 'name' => '题库导出', 'type' => 'button', 'parent_code' => 'questions'],
            ['code' => 'papers', 'name' => '试卷管理', 'type' => 'menu', 'menu_path' => '/admin/papers', 'sort' => 70],
            ['code' => 'reports', 'name' => '统计报表', 'type' => 'menu', 'menu_path' => '/admin/reports', 'sort' => 80],
            ['code' => 'settings', 'name' => '系统配置', 'type' => 'menu', 'menu_path' => '/admin/settings', 'sort' => 90],
            ['code' => 'logs', 'name' => '操作日志', 'type' => 'menu', 'menu_path' => '/admin/logs', 'sort' => 100],
        ];

        foreach ($permissions as $permission) {
            Permission::query()->updateOrCreate(['code' => $permission['code']], $permission);
        }

        $teacherPermissions = Permission::query()
            ->whereIn('code', ['dashboard', 'classes', 'banks', 'banks.create', 'banks.update', 'banks.delete', 'banks.share', 'questions', 'questions.import', 'questions.export', 'papers', 'reports'])
            ->pluck('id');

        foreach ($teacherPermissions as $permissionId) {
            DB::table('role_permissions')->updateOrInsert([
                'role' => 'teacher',
                'permission_id' => $permissionId,
            ], [
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        $settings = [
            'site.name' => 'QuickQuiz',
            'register.enabled' => true,
            'invite.required' => true,
            'score.single' => 1,
            'score.multiple' => 2,
            'score.judge' => 1,
            'score.blank' => 2,
            'test.default_duration_minutes' => 45,
            'mail.enabled' => false,
            'sms.enabled' => false,
        ];

        foreach ($settings as $key => $value) {
            DB::table('system_settings')->updateOrInsert([
                'key' => $key,
            ], [
                'value' => json_encode($value, JSON_UNESCAPED_UNICODE),
                'group' => str_contains($key, '.') ? explode('.', $key)[0] : 'general',
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        DB::table('operation_logs')->insert([
            'user_id' => $admin->id,
            'action' => 'system.seeded',
            'target_type' => 'system',
            'target_id' => null,
            'ip' => null,
            'payload' => json_encode(['message' => 'Initial roles, permissions, and settings seeded'], JSON_UNESCAPED_UNICODE),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
