<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class GenerateKeys extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:generate-keys {--path= : Custom path for key directory}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate RSA key pair for OIDC (RS256)';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $keyDir = $this->getKeyDirectory();

        if (!is_dir($keyDir)) {
            mkdir($keyDir, 0700, true);
        }

        $privatePath = "$keyDir/private.pem";
        $publicPath  = "$keyDir/public.pem";

        if (file_exists($privatePath) || file_exists($publicPath)) {
            $this->warn('Keys already exist. Aborting.');
            return 1;
        }

        $this->info("Generating RSA key pair...");

        // Generate 2048-bit RSA private key
        $res = openssl_pkey_new([
            'private_key_bits' => 2048,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ]);

        openssl_pkey_export($res, $privateKey);
        file_put_contents($privatePath, $privateKey);
        chmod($privatePath, 0600);

        $pubKeyDetails = openssl_pkey_get_details($res);
        file_put_contents($publicPath, $pubKeyDetails['key']);
        chmod($publicPath, 0644);

        $this->info("✅ Keys generated:");
        $this->line("- Private: $privatePath");
        $this->line("- Public : $publicPath");

        return 0;
    }

    /**
     * Get the key directory path.
     */
    protected function getKeyDirectory(): string
    {
        // Use custom path if provided
        if ($customPath = $this->option('path')) {
            return $customPath;
        }

        // Use test directory if in testing environment
        if (app()->environment('testing')) {
            return storage_path('testing/oauth');
        }

        // Default production path
        return storage_path('oauth');
    }
}
