<?php

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Migrations\Migration;
use App\Support\AdminAuthorizationRegistry;
use App\Support\AdminPermissionBridge;

return new class extends Migration
{
    public function up(): void
    {
        $now = Carbon::now();
        $actionCatalogId = (int) DB::table('admin_action_catalog')->where('code', 'manage')->value('id');
        $adminUserMenuId = (int) DB::table('admin_menus')->where('code', 'system.admin_user')->value('id');

        if ($adminUserMenuId > 0) {
            $adminUserMenu = DB::table('admin_menus')->where('id', $adminUserMenuId)->first();
            DB::table('admin_menus')->updateOrInsert(
                ['code' => 'system.admin_role'],
                [
                    'parent_id' => $adminUserMenu->parent_id,
                    'menu_type' => 'page',
                    'name' => '角色管理',
                    'path' => '/admin/admin-roles',
                    'route_name' => 'admin.system.admin-roles',
                    'component' => 'system/admin-roles',
                    'icon' => 'shield-check',
                    'active_menu_code' => null,
                    'sort_order' => ((int) $adminUserMenu->sort_order) + 1,
                    'is_visible' => true,
                    'is_cache' => false,
                    'is_external' => false,
                    'status' => 1,
                    'meta_json' => null,
                    'created_at' => $now,
                    'updated_at' => $now,
                ],
            );
        }

        $menuId = (int) DB::table('admin_menus')->where('code', 'system.admin_role')->value('id');

        if ($actionCatalogId > 0 && $menuId > 0) {
            DB::table('admin_menu_actions')->updateOrInsert(
                ['permission_code' => 'system.admin_role.manage'],
                [
                    'menu_id' => $menuId,
                    'action_id' => $actionCatalogId,
                    'name' => '角色权限管理',
                    'status' => 1,
                    'created_at' => $now,
                    'updated_at' => $now,
                ],
            );
        }

        $menuActionIds = DB::table('admin_menu_actions')->pluck('id', 'permission_code');
        foreach (AdminAuthorizationRegistry::resources() as $resource) {
            $resourceId = DB::table('admin_api_resources')
                ->where('code', $resource['code'])
                ->value('id');

            if ($resourceId === null) {
                continue;
            }

            DB::table('admin_api_resource_bindings')
                ->where('api_resource_id', (int) $resourceId)
                ->delete();

            foreach ($resource['permission_codes'] as $permissionCode) {
                $menuActionId = $menuActionIds[$permissionCode] ?? null;
                if ($menuActionId === null) {
                    continue;
                }

                DB::table('admin_api_resource_bindings')->insert([
                    'api_resource_id' => (int) $resourceId,
                    'menu_action_id' => (int) $menuActionId,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }
        }

        $adminRoleSlug = 'prd.admin_role.manage';
        $adminUserSlug = 'prd.admin_user.manage';
        $roleIds = DB::table('admin_role_legacy_permissions')
            ->where('permission_slug', $adminUserSlug)
            ->pluck('role_id')
            ->all();

        foreach ($roleIds as $roleId) {
            DB::table('admin_role_legacy_permissions')->updateOrInsert(
                [
                    'role_id' => (int) $roleId,
                    'permission_slug' => $adminRoleSlug,
                ],
                [
                    'created_at' => $now,
                    'updated_at' => $now,
                ],
            );

            foreach (AdminPermissionBridge::menuActionCodesForLegacy($adminRoleSlug) as $permissionCode) {
                $menuActionId = $menuActionIds[$permissionCode] ?? null;
                if ($menuActionId === null) {
                    continue;
                }

                DB::table('admin_role_menu_actions')->updateOrInsert([
                    'role_id' => (int) $roleId,
                    'menu_action_id' => (int) $menuActionId,
                ]);
            }
        }
    }

    public function down(): void
    {
        // 不回滚授权数据，避免删除线上已经显式授予的角色管理权限。
    }
};
