<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * Update all roles (id 1 & 2) and all permissions to use 'api' guard_name
     * instead of 'web', to align with Spatie Laravel Permission v7 strict
     * guard matching behaviour for SPA/API-based requests.
     */
    public function up(): void
    {
        DB::table('roles')->where('id', 1)->update(['guard_name' => 'api']);
        DB::table('roles')->where('id', 2)->update(['guard_name' => 'api']);
        DB::table('permissions')->where('id', '>', 0)->update(['guard_name' => 'api']);

        // Clear Spatie permission cache so changes take effect immediately
        app()['cache']->forget('spatie.permission.cache');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        DB::table('roles')->where('id', 1)->update(['guard_name' => 'web']);
        DB::table('roles')->where('id', 2)->update(['guard_name' => 'web']);
        DB::table('permissions')->where('id', '>', 0)->update(['guard_name' => 'web']);

        // Clear Spatie permission cache so rollback takes effect immediately
        app()['cache']->forget('spatie.permission.cache');
    }
};
