import * as readline from 'readline';
import { Command } from 'commander';
import chalk from 'chalk';
import { requireConfig } from '../config';
import { apiRequest } from '../api';

interface RotateResponse {
  clientId: string;
  clientSecret: string;
  rotatedAt?: string;
}

function prompt(rl: readline.Interface, question: string): Promise<string> {
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      resolve(answer.trim());
    });
  });
}

export function registerRotateCredentials(program: Command): void {
  program
    .command('rotate-credentials')
    .description('Rotate credentials for an agent (invalidates current secret)')
    .requiredOption('--agent-id <id>', 'Agent ID whose credentials to rotate')
    .action(async (options: { agentId: string }) => {
      const config = requireConfig();

      const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
      });

      try {
        console.log(
          chalk.yellow('⚠') +
            '  This will invalidate the current secret for agent ' +
            chalk.cyan(options.agentId),
        );

        const answer = await prompt(
          rl,
          chalk.bold('This will invalidate the current secret. Continue? [y/N] '),
        );

        if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {
          console.log(chalk.dim('Aborted.'));
          return;
        }

        const data = await apiRequest<RotateResponse>(
          config,
          `/agents/${options.agentId}/credentials/rotate`,
          { method: 'POST' },
        );

        console.log();
        console.log(chalk.green('✓') + ' Credentials rotated successfully');
        console.log();
        console.log(chalk.bold('Client ID:     ') + chalk.cyan(data.clientId));
        console.log(
          chalk.bold('Client Secret: ') + chalk.yellow(data.clientSecret),
        );
        console.log();
        console.log(
          chalk.dim(
            'Store the new client secret securely — it will not be shown again.',
          ),
        );
        if (data.rotatedAt !== undefined) {
          console.log(
            chalk.dim('Rotated at: ') + chalk.dim(data.rotatedAt),
          );
        }
      } catch (err) {
        console.error(
          chalk.red('Error:'),
          err instanceof Error ? err.message : String(err),
        );
        process.exit(1);
      } finally {
        rl.close();
      }
    });
}
