<?php

namespace App\Console\Commands;

use App\Models\Commons\Menu;
use Illuminate\Console\Command;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\PermissionRegistrar;

class SeedMenuPermissions extends Command
{
    protected $signature = 'sam:seed-menu-perms {--tenant=} {--guard=api}';

    protected $description = 'Create missing permissions menu:{id}.{action} for all menus';

    public function handle(): int
    {
        $tenant = $this->option('tenant') ? (int) $this->option('tenant') : null;
        $guard = $this->option('guard') ?: 'api';
        $actions = config('authz.menu_actions', ['view', 'create', 'update', 'delete', 'approve']);

        $menus = Menu::query()
            ->when($tenant !== null, fn ($q) => $q->where('tenant_id', $tenant))
            ->get();

        $count = 0;

        foreach ($menus as $m) {
            app(PermissionRegistrar::class)->setPermissionsTeamId((int) $m->tenant_id);

            foreach ($actions as $act) {
                Permission::firstOrCreate([
                    'tenant_id' => (int) $m->tenant_id,
                    'guard_name' => $guard,
                    'name' => "menu:{$m->id}.{$act}",
                ]);
                $count++;
            }
        }

        app(PermissionRegistrar::class)->forgetCachedPermissions();
        $this->info("Ensured {$count} permissions.");

        return self::SUCCESS;
    }
}
