<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $now = Carbon::now();

        $serviceMenuId = (int) DB::table('admin_menus')->where('code', 'service')->value('id');
        $manageActionId = (int) DB::table('admin_action_catalog')->where('code', 'manage')->value('id');

        if ($serviceMenuId > 0) {
            DB::table('admin_menus')->updateOrInsert(
                ['code' => 'service.currency'],
                [
                    'parent_id' => $serviceMenuId,
                    'menu_type' => 'page',
                    'name' => '币种管理',
                    'path' => '/admin/settings/currencies',
                    'route_name' => 'admin.settings.currencies',
                    'component' => 'settings/currencies',
                    'icon' => null,
                    'active_menu_code' => null,
                    'sort_order' => 70,
                    'is_visible' => false,
                    'is_cache' => false,
                    'is_external' => false,
                    'status' => 1,
                    'meta_json' => null,
                    'created_at' => $now,
                    'updated_at' => $now,
                ],
            );
        }

        $currencyMenuId = (int) DB::table('admin_menus')->where('code', 'service.currency')->value('id');
        if ($currencyMenuId > 0 && $manageActionId > 0) {
            DB::table('admin_menu_actions')->updateOrInsert(
                ['permission_code' => 'service.currency.manage'],
                [
                    'menu_id' => $currencyMenuId,
                    'action_id' => $manageActionId,
                    'name' => '币种管理',
                    'status' => 1,
                    'created_at' => $now,
                    'updated_at' => $now,
                ],
            );
        }

        if (Schema::hasTable('admin_permissions')) {
            DB::table('admin_permissions')->updateOrInsert(
                ['slug' => 'prd.currency.manage'],
                [
                    'name' => '币种管理·可管理',
                    'updated_at' => $now,
                    'created_at' => $now,
                ],
            );
        }

        $currencyActionId = DB::table('admin_menu_actions')
            ->where('permission_code', 'service.currency.manage')
            ->value('id');

        if ($currencyActionId === null) {
            return;
        }

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

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

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

        $currencyResourceIds = DB::table('admin_api_resources')
            ->whereIn('code', [
                'admin.currencies.index',
                'admin.currencies.store',
                'admin.currencies.update',
                'admin.currencies.destroy',
            ])
            ->pluck('id')
            ->all();

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

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

        $roleResourceRows = DB::table('admin_role_menu_actions as rma')
            ->join('admin_api_resource_bindings as arb', 'arb.menu_action_id', '=', 'rma.menu_action_id')
            ->whereIn('arb.api_resource_id', $currencyResourceIds)
            ->select('rma.role_id', 'arb.api_resource_id')
            ->distinct()
            ->get();

        foreach ($roleResourceRows as $row) {
            DB::table('admin_role_api_resources')->updateOrInsert([
                'role_id' => (int) $row->role_id,
                'api_resource_id' => (int) $row->api_resource_id,
            ], []);
        }
    }

    public function down(): void
    {
        // 不自动回滚线上角色与资源绑定，避免误删已调整的授权。
    }
};
