<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use App\Support\AdminPermissionBridge;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('admin_role_legacy_permissions', function (Blueprint $table): void {
            $table->foreignId('role_id')->constrained('admin_roles')->cascadeOnDelete();
            $table->string('permission_slug', 128);
            $table->timestamps();

            $table->primary(['role_id', 'permission_slug'], 'pk_admin_role_legacy_permissions');
        });

        $now = now();
        $roleCodes = DB::table('admin_role_menu_actions as rma')
            ->join('admin_menu_actions as ma', 'ma.id', '=', 'rma.menu_action_id')
            ->where('ma.status', 1)
            ->select('rma.role_id', 'ma.permission_code')
            ->get()
            ->groupBy('role_id');

        foreach ($roleCodes as $roleId => $rows) {
            $slugs = AdminPermissionBridge::legacySlugsGrantedByMenuActionCodes(
                $rows->pluck('permission_code')->all(),
            );
            foreach ($slugs as $slug) {
                DB::table('admin_role_legacy_permissions')->insert([
                    'role_id' => (int) $roleId,
                    'permission_slug' => $slug,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('admin_role_legacy_permissions');
    }
};
