<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;

class GenerateApiToken extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'api:generate-token {user? : The user ID or email/username} {--name= : Token name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate an API token for a user using Laravel Sanctum';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $userIdentifier = $this->argument('user');
        
        if (!$userIdentifier) {
            $userIdentifier = $this->ask('Enter user ID, email, or username');
        }

        // Find user by ID, email, or username
        $user = User::where('id', $userIdentifier)
            ->orWhere('email', $userIdentifier)
            ->orWhere('username', $userIdentifier)
            ->first();

        if (!$user) {
            $this->error('User not found!');
            return 1;
        }

        $tokenName = $this->option('name') ?: $this->ask('Enter token name (e.g., "external-system")', 'api-token');

        $token = $user->createToken($tokenName);

        $this->info('API Token generated successfully!');
        $this->newLine();
        $this->line('User: ' . $user->name . ' (' . $user->email . ')');
        $this->line('Token Name: ' . $tokenName);
        $this->newLine();
        $this->warn('Token (save this - it will not be shown again):');
        $this->line($token->plainTextToken);
        $this->newLine();
        $this->info('Use this token in API requests:');
        $this->line('Authorization: Bearer ' . $token->plainTextToken);

        return 0;
    }
}
