<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * 確保 super-admin 角色擁有所有權限
     */
    public function up(): void
    {
        // 取得 super-admin 角色
        $role = DB::table('roles')->where('name', 'super-admin')->first();
        if (!$role) {
            return; // 角色不存在則跳過
        }

        // 取得所有權限
        $permissions = DB::table('permissions')->pluck('id');
        if ($permissions->isEmpty()) {
            return;
        }

        // 清除該角色現有的權限
        DB::table('role_has_permissions')
            ->where('role_id', $role->id)
            ->delete();

        // 指派所有權限給 super-admin
        $inserts = $permissions->map(fn ($permissionId) => [
            'permission_id' => $permissionId,
            'role_id' => $role->id,
        ])->toArray();

        DB::table('role_has_permissions')->insert($inserts);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // 此 Migration 不需要復原邏輯
    }
};
