import chalk from 'chalk';
import { createInterface } from 'readline';
import { saveCredentials, extractAuthCookies, extractUsername } from '../lib/credentials.js';

/**
 * Read multi-line input until empty line
 */
async function readInput(prompt) {
  const rl = createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  
  return new Promise((resolve) => {
    rl.question(prompt, (answer) => {
      rl.close();
      resolve(answer.trim());
    });
  });
}

export async function authCommand() {
  console.log(chalk.cyan.bold('\n📱 TextNow Authentication\n'));
  console.log(chalk.yellow('To authenticate, you need to extract cookies from your browser.\n'));
  
  console.log(chalk.white('Instructions:'));
  console.log(chalk.gray('─────────────────────────────────────────────'));
  console.log(chalk.white('1.') + ' Log into ' + chalk.blue('https://textnow.com'));
  console.log(chalk.white('2.') + ' Open DevTools (' + chalk.cyan('F12') + ' or ' + chalk.cyan('Cmd+Option+I') + ')');
  console.log(chalk.white('3.') + ' Go to the ' + chalk.cyan('Console') + ' tab');
  console.log(chalk.white('4.') + ' Run: ' + chalk.green('document.cookie'));
  console.log(chalk.white('5.') + ' Copy the entire output');
  console.log(chalk.white('6.') + ' Paste below when prompted');
  console.log(chalk.gray('─────────────────────────────────────────────\n'));
  
  const cookies = await readInput(chalk.cyan('Paste your cookies: '));
  
  if (!cookies) {
    console.log(chalk.red('\n❌ No cookies provided. Authentication cancelled.'));
    process.exit(1);
  }
  
  // Validate that we got something useful
  const authCookies = extractAuthCookies(cookies);
  
  if (!authCookies.connectSid && !authCookies.tnSessionId) {
    console.log(chalk.yellow('\n⚠️  Warning: No session cookie found (connect.sid or tn_session_id).'));
    console.log(chalk.yellow('   Authentication may not work correctly.'));
  }
  
  // Try to extract username from cookies
  let username = extractUsername(cookies);
  
  if (!username) {
    username = await readInput(chalk.cyan('\nEnter your TextNow username (optional, press Enter to skip): '));
  }
  
  // Save credentials
  const saved = await saveCredentials({
    username: username || null,
    cookies,
  });
  
  console.log(chalk.green('\n✅ Credentials saved successfully!'));
  console.log(chalk.gray(`   Location: ~/.textnow/credentials.json`));
  console.log(chalk.gray(`   Saved at: ${saved.savedAt}`));
  
  // Show what cookies we found
  console.log(chalk.cyan('\nDetected auth cookies:'));
  if (authCookies.connectSid) console.log(chalk.gray('   • connect.sid: ') + chalk.green('✓'));
  if (authCookies.csrf) console.log(chalk.gray('   • _csrf: ') + chalk.green('✓'));
  if (authCookies.xsrfToken) console.log(chalk.gray('   • XSRF-TOKEN: ') + chalk.green('✓'));
  if (authCookies.tnSessionId) console.log(chalk.gray('   • tn_session_id: ') + chalk.green('✓'));
  
  console.log(chalk.cyan('\nRun ') + chalk.white('textnow whoami') + chalk.cyan(' to verify your authentication.\n'));
}
