<?php

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

/**
 * 信用流水 API 注册到 admin_api_resources（已有库增量同步，避免 500 api_resource_not_configured）。
 */
return new class extends Migration
{
    /** @var list<string> */
    private const RESOURCE_CODES = [
        'admin.credit-ledger.index',
        'admin.settlement-payments.index',
        'admin.settlement-adjustments.index',
        'admin.settlement-reports.summary',
        'admin.settlement-reports.show',
    ];

    public function up(): void
    {
        $now = Carbon::now();
        $menuActionIds = DB::table('admin_menu_actions')->pluck('id', 'permission_code');
        $byCode = collect(AdminAuthorizationRegistry::resources())->keyBy('code');

        foreach (self::RESOURCE_CODES as $code) {
            $resource = $byCode->get($code);
            if (! is_array($resource)) {
                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,
                ]);
            }
        }
    }

    public function down(): void
    {
        foreach (self::RESOURCE_CODES as $code) {
            $resourceId = DB::table('admin_api_resources')->where('code', $code)->value('id');
            if ($resourceId === null) {
                continue;
            }

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