<?php

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

        $resourceId = DB::table('admin_api_resources')
            ->where('code', 'admin.tickets.index')
            ->value('id');

        if ($resourceId === null) {
            $resourceId = DB::table('admin_api_resources')->insertGetId([
                'code' => 'admin.tickets.index',
                'module_code' => 'ticket',
                'name' => '后台注单列表',
                'http_method' => 'GET',
                'uri_pattern' => '/api/v1/admin/tickets',
                'route_name' => 'api.v1.admin.tickets.index',
                'auth_mode' => 'permission_required',
                'is_audit_required' => false,
                'status' => 1,
                'meta_json' => null,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }

        $menuActionId = DB::table('admin_menu_actions')
            ->where('permission_code', 'service.tickets.view')
            ->value('id');

        if ($menuActionId !== null) {
            $exists = DB::table('admin_api_resource_bindings')
                ->where('api_resource_id', $resourceId)
                ->where('menu_action_id', $menuActionId)
                ->exists();

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

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

        if ($resourceId !== null) {
            DB::table('admin_api_resource_bindings')
                ->where('api_resource_id', $resourceId)
                ->delete();

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