<?php

namespace Modules\Identity\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Modules\Identity\Enums\TokenAbility;

class IssueFastApiAgentTokenCommand extends Command
{
    protected $signature = 'identity:issue-agent-token
        {--email=fastapi-agent@system.internal : Email identifying the FastAPI agent service account}
        {--name=fastapi-agent : Sanctum token name}';

    protected $description = 'Provision a Sanctum token for the FastAPI AI agent, scoped to its restricted ability set';

    public function handle(): int
    {
        $email = $this->option('email');
        $tokenName = $this->option('name');

        $agent = User::firstOrCreate(
            ['email' => $email],
            [
                'name' => 'FastAPI Agent',
                'password' => Str::password(40),
            ],
        );

        $agent->tokens()->where('name', $tokenName)->delete();

        $token = $agent->createToken($tokenName, TokenAbility::fastApiAgentAbilities());

        $this->components->info('FastAPI agent token issued.');
        $this->line($token->plainTextToken);

        return self::SUCCESS;
    }
}
