<?php

namespace Database\Seeders;

use App\Models\Permission;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class AssignLoanDisbursementPermissionSeeder extends Seeder
{
    public function run(): void
    {
        // Find the loans.disburse permission
        $permission = Permission::where('slug', 'loans.disburse')->first();

        if (!$permission) {
            $this->command->error('loans.disburse permission not found!');
            return;
        }

        // Get all users
        $users = User::all();

        foreach ($users as $user) {
            // Check if user already has this permission
            $exists = DB::table('permission_user')
                ->where('user_id', $user->id)
                ->where('permission_id', $permission->id)
                ->exists();

            if (!$exists) {
                // Assign the permission with the disburse action
                DB::table('permission_user')->insert([
                    'user_id' => $user->id,
                    'permission_id' => $permission->id,
                    'actions' => json_encode(['disburse']),
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                $this->command->info("Assigned loans.disburse permission to user: {$user->name}");
            }
        }

        $this->command->info('Loan disbursement permission assigned to all users!');
    }
}
