<?php

use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        foreach (['roles', 'permissions', 'permission_role', 'role_user', 'role_has_permissions', 'model_has_roles'] as $table) {
            if (! Schema::hasTable($table)) {
                return;
            }
        }

        DB::transaction(function (): void {
            DB::table('roles')
                ->where(fn ($query) => $query->whereNull('guard_name')->orWhere('guard_name', '!=', 'web'))
                ->update(['guard_name' => 'web']);
            DB::table('permissions')
                ->where(fn ($query) => $query->whereNull('guard_name')->orWhere('guard_name', '!=', 'web'))
                ->update(['guard_name' => 'web']);

            DB::table('role_has_permissions')->delete();
            DB::table('permission_role')
                ->orderBy('permission_id')
                ->orderBy('role_id')
                ->chunk(500, function ($rows): void {
                    if ($rows->isEmpty()) {
                        return;
                    }

                    DB::table('role_has_permissions')->insert(
                        $rows->map(fn ($row): array => [
                            'permission_id' => $row->permission_id,
                            'role_id' => $row->role_id,
                        ])->all(),
                    );
                });

            DB::table('model_has_roles')->where('model_type', User::class)->delete();
            DB::table('role_user')
                ->orderBy('role_id')
                ->orderBy('user_id')
                ->chunk(500, function ($rows): void {
                    if ($rows->isEmpty()) {
                        return;
                    }

                    DB::table('model_has_roles')->insert(
                        $rows->map(fn ($row): array => [
                            'role_id' => $row->role_id,
                            'model_type' => User::class,
                            'model_id' => $row->user_id,
                        ])->all(),
                    );
                });
        });

        $store = config('permission.cache.store');
        cache()->store($store !== 'default' ? $store : null)->forget(config('permission.cache.key'));
    }

    public function down(): void
    {
        // Data-only cutover checkpoint. Legacy comparison pivots remain intact,
        // so a rollback of application code does not require reversing data.
    }
};
