<?php

use Illuminate\Database\Migrations\Migration;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $permissionId = \DB::table('permissions')->insertOrIgnore([
            'name' => 'departments',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        if (! $permissionId) {
            $permissionId = \DB::table('permissions')->where('name', 'departments')->value('id');
        }

        if ($permissionId) {
            $roleIds = \DB::table('roles')->pluck('id');
            foreach ($roleIds as $roleId) {
                \DB::table('role_permissions')->insertOrIgnore([
                    'role_id' => $roleId,
                    'permission_id' => $permissionId,
                ]);
            }
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $permissionId = \DB::table('permissions')->where('name', 'departments')->value('id');
        if ($permissionId) {
            \DB::table('role_permissions')->where('permission_id', $permissionId)->delete();
            \DB::table('permissions')->where('id', $permissionId)->delete();
        }
    }
};
