import { Command, Flags } from '@oclif/core';
import chalk from 'chalk';
import { generateKeyPairSync } from 'node:crypto';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import ora from 'ora';
export default class Keys extends Command {
    static description = 'Generate RSA private key and public key (defaults to ./backend/.keys)';
    static examples = [
        '<%= config.bin %> <%= command.id %>',
        '<%= config.bin %> <%= command.id %> --out ./keys',
    ];
    static flags = {
        out: Flags.string({
            char: 'o',
            description: 'Output directory for the key files (default: backend/.keys)',
        }),
    };
    async run() {
        const { flags } = await this.parse(Keys);
        this.log('');
        this.log(chalk.bold.cyan('━━━ RSA Key Generation ━━━'));
        this.log('');
        const spinner = ora('Generating RSA 2048-bit keypair').start();
        const { privateKey, publicKey } = generateKeyPairSync('rsa', {
            modulusLength: 2048,
            privateKeyEncoding: { format: 'pem', type: 'pkcs1' },
            publicKeyEncoding: { format: 'pem', type: 'pkcs1' },
        });
        spinner.succeed('Keypair generated');
        const dir = flags.out
            ? resolve(flags.out)
            : join(process.cwd(), 'backend', '.keys');
        mkdirSync(dir, { recursive: true });
        const privatePath = join(dir, 'oauth-private.key');
        const publicPath = join(dir, 'oauth-public.key');
        writeFileSync(privatePath, privateKey);
        writeFileSync(publicPath, publicKey);
        this.log('');
        this.log(chalk.green('✔'), `Private key saved in ${chalk.bold(privatePath)}`);
        this.log(chalk.green('✔'), `Public key saved in  ${chalk.bold(publicPath)}`);
        this.log('');
    }
}
