<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $permissionIds = DB::table('permissions')
            ->whereIn('slug', ['renewals.view', 'renewals.manage'])
            ->pluck('id');

        DB::table('roles')
            ->where('slug', 'typist')
            ->pluck('id')
            ->each(function (int $roleId) use ($permissionIds): void {
                foreach ($permissionIds as $permissionId) {
                    DB::table('role_permissions')->insertOrIgnore([
                        'role_id' => $roleId,
                        'permission_id' => $permissionId,
                    ]);
                }
            });
    }

    public function down(): void
    {
        $viewPermissionId = DB::table('permissions')->where('slug', 'renewals.view')->value('id');
        $typistRoleIds = DB::table('roles')->where('slug', 'typist')->pluck('id');

        if ($viewPermissionId && $typistRoleIds->isNotEmpty()) {
            DB::table('role_permissions')
                ->where('permission_id', $viewPermissionId)
                ->whereIn('role_id', $typistRoleIds)
                ->delete();
        }
    }
};
