import type { Command } from 'commander';
import { loadStoredOpenAIAuth, loginOpenAI } from '../auth/index.js';

export function registerOpenaiAuthCommand(program: Command): void {
  program
    .command('openai-auth')
    .description('Authenticate OpenAI (ChatGPT Plus/Pro) via OAuth device flow')
    .action(async () => {
      const existing = loadStoredOpenAIAuth();
      if (existing) {
        console.log('OpenAI OAuth token already exists.');
        console.log('Delete ~/.config/flynn/auth.json openai entry if you want to re-authenticate.');
        process.exit(0);
      }

      console.log('Starting OpenAI OAuth device flow...');
      console.log('');

      try {
        await loginOpenAI((userCode, verificationUri) => {
          console.log(`Please visit: ${verificationUri}`);
          console.log(`Enter code:  ${userCode}`);
          console.log('');
          console.log('Waiting for authorization...');
        });

        console.log('');
        console.log('OpenAI authentication successful! Token stored.');
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.error(`OpenAI login failed: ${message}`);
        process.exit(1);
      }
    });
}
