<?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();

        $resource = collect(AdminAuthorizationRegistry::resources())
            ->firstWhere('code', 'admin.dashboard.analytics');

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

        $resourceId = DB::table('admin_api_resources')
            ->where('code', 'admin.dashboard.analytics')
            ->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' => 'admin.dashboard.analytics',
                '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) {
            $actionId = DB::table('admin_menu_actions')
                ->where('permission_code', $permissionCode)
                ->value('id');
            if ($actionId === null) {
                continue;
            }

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

    public function down(): void
    {
        $resourceId = DB::table('admin_api_resources')
            ->where('code', 'admin.dashboard.analytics')
            ->value('id');

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

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