<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Support\Facades\DB;

class AssignInventoryPermissionsToRoles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'assign:inventory-permissions {role_id?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Assign inventory permissions to specific roles';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $roleId = $this->argument('role_id');

        // Get inventory permissions
        $permissions = Permission::where('group', 'inventory')->get();

        if ($permissions->isEmpty()) {
            $this->error('No inventory permissions found. Please run create:inventory-permissions first.');
            return Command::FAILURE;
        }

        $this->info('Found ' . $permissions->count() . ' inventory permissions.');

        // Define roles that should have inventory permissions
        $rolesToUpdate = [];

        if ($roleId) {
            // If role_id is provided, only update that role
            $role = Role::find($roleId);
            if (!$role) {
                $this->error("Role with ID {$roleId} not found.");
                return Command::FAILURE;
            }
            $rolesToUpdate[] = $role;
        } else {
            // Otherwise, update predefined roles
            $rolesToUpdate = Role::whereIn('id', [10, 11, 12, 13])->get();

            if ($rolesToUpdate->isEmpty()) {
                $this->error('No matching roles found.');
                return Command::FAILURE;
            }
        }

        DB::beginTransaction();

        try {
            foreach ($rolesToUpdate as $role) {
                $this->info("Assigning inventory permissions to role: {$role->name} (ID: {$role->id})");

                // Get existing permissions for this role
                $existingPermissions = $role->permissions()->pluck('permissions.id')->toArray();

                // Add inventory permissions to existing permissions
                $newPermissions = array_merge($existingPermissions, $permissions->pluck('id')->toArray());

                // Remove duplicates
                $newPermissions = array_unique($newPermissions);

                // Sync permissions
                $role->permissions()->sync($newPermissions);

                $this->info("Successfully assigned " . $permissions->count() . " inventory permissions to role: {$role->name}");
            }

            DB::commit();
            $this->info('All permissions assigned successfully.');

            return Command::SUCCESS;
        } catch (\Exception $e) {
            DB::rollBack();
            $this->error("Error assigning permissions: {$e->getMessage()}");

            return Command::FAILURE;
        }
    }
}
