<?php

namespace App\Console\Commands;

use App\Models\ApiClient;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

class GenerateApiClient extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'api-client:generate {name : The name of the API client}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a new API client and display their API Key';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $name = $this->argument('name');
        
        // Generate secure 32 character key with prefix
        $plainKey = 'dv_' . Str::random(32);
        $hashedKey = hash('sha256', $plainKey);

        $client = ApiClient::create([
            'name' => $name,
            'api_key' => $hashedKey,
            'is_active' => true,
        ]);

        $this->info("API Client successfully created!");
        $this->table(
            ['ID', 'Name', 'Status'],
            [[$client->id, $client->name, 'Active']]
        );

        $this->warn("Here is the API Key. Copy it now, as it will NOT be shown again for security reasons:");
        $this->line($plainKey);

        return self::SUCCESS;
    }
}
