<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $now = Carbon::now();
        $actionViewId = DB::table('admin_action_catalog')->where('code', 'view')->value('id');
        if ($actionViewId === null) {
            return;
        }

        $serviceMenuId = DB::table('admin_menus')->where('code', 'service')->value('id');
        if ($serviceMenuId === null) {
            return;
        }

        $reportMenuId = DB::table('admin_menus')->where('code', 'service.report')->value('id');
        if ($reportMenuId === null) {
            $reportMenuId = DB::table('admin_menus')->insertGetId([
                'parent_id' => $serviceMenuId,
                'menu_type' => 'page',
                'code' => 'service.report',
                'name' => '报表中心',
                'path' => '/admin/reports',
                'route_name' => 'admin.reports.index',
                'component' => 'service/reports',
                'icon' => null,
                'active_menu_code' => null,
                'sort_order' => 50,
                'is_visible' => true,
                'is_cache' => false,
                'is_external' => false,
                'status' => 1,
                'meta_json' => null,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }

        $menuActionIds = DB::table('admin_menu_actions')->pluck('id', 'permission_code');
        if (! isset($menuActionIds['service.report.view'])) {
            DB::table('admin_menu_actions')->insert([
                'menu_id' => (int) $reportMenuId,
                'action_id' => (int) $actionViewId,
                'permission_code' => 'service.report.view',
                'name' => '报表中心查看',
                'status' => 1,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
            $menuActionIds = DB::table('admin_menu_actions')->pluck('id', 'permission_code');
        }

        $reportResourceCodes = [
            'admin.reports.daily-profit',
            'admin.reports.player-win-loss',
            'admin.reports.play-dimension',
            'admin.reports.rebate-commission',
            'admin.report-jobs.index',
            'admin.report-jobs.store',
            'admin.report-jobs.show',
            'admin.report-jobs.download',
        ];

        foreach (AdminAuthorizationRegistry::resources() as $resource) {
            if (! in_array($resource['code'], $reportResourceCodes, true)) {
                continue;
            }

            $resourceId = DB::table('admin_api_resources')
                ->where('code', $resource['code'])
                ->value('id');

            $payload = [
                'module_code' => $resource['module_code'],
                'name' => $resource['name'],
                'http_method' => $resource['http_method'],
                'uri_pattern' => $resource['uri_pattern'],
                'route_name' => $resource['route_name'],
                'auth_mode' => $resource['auth_mode'],
                'is_audit_required' => $resource['is_audit_required'],
                'status' => 1,
                'meta_json' => null,
                'updated_at' => $now,
            ];

            if ($resourceId === null) {
                $resourceId = DB::table('admin_api_resources')->insertGetId($payload + [
                    'code' => $resource['code'],
                    'created_at' => $now,
                ]);
            } else {
                DB::table('admin_api_resources')
                    ->where('id', (int) $resourceId)
                    ->update($payload);
            }

            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,
                ]);
            }
        }

        $superRoleId = DB::table('admin_roles')->where('slug', 'super_admin')->value('id');
        if ($superRoleId !== null && isset($menuActionIds['service.report.view'])) {
            DB::table('admin_role_menu_actions')->updateOrInsert([
                'role_id' => (int) $superRoleId,
                'menu_action_id' => (int) $menuActionIds['service.report.view'],
            ]);
        }

    }

    public function down(): void
    {
        $codes = [
            'admin.reports.daily-profit',
            'admin.reports.player-win-loss',
            'admin.reports.play-dimension',
            'admin.reports.rebate-commission',
            'admin.report-jobs.index',
            'admin.report-jobs.store',
            'admin.report-jobs.show',
            'admin.report-jobs.download',
        ];

        $resourceIds = DB::table('admin_api_resources')->whereIn('code', $codes)->pluck('id');
        foreach ($resourceIds as $resourceId) {
            DB::table('admin_api_resource_bindings')->where('api_resource_id', (int) $resourceId)->delete();
            DB::table('admin_api_resources')->where('id', (int) $resourceId)->delete();
        }

        $menuActionId = DB::table('admin_menu_actions')->where('permission_code', 'service.report.view')->value('id');
        if ($menuActionId !== null) {
            DB::table('admin_role_menu_actions')->where('menu_action_id', (int) $menuActionId)->delete();
            DB::table('admin_menu_actions')->where('id', (int) $menuActionId)->delete();
        }

        DB::table('admin_menus')->where('code', 'service.report')->delete();
    }
};
