import chalk from 'chalk';
import { loadCredentials, updateCredentials } from '../lib/credentials.js';
import { getUserProfile } from '../lib/api.js';

export async function whoamiCommand() {
  const credentials = await loadCredentials();
  
  if (!credentials) {
    console.log(chalk.red('\n❌ Not authenticated. Run `textnow auth` first.\n'));
    process.exit(1);
  }
  
  console.log(chalk.cyan.bold('\n📱 TextNow Account Info\n'));
  
  // Show cached info
  if (credentials.username) {
    console.log(chalk.gray('Username (cached): ') + chalk.white(credentials.username));
  }
  
  // Try to fetch fresh profile data
  console.log(chalk.gray('Fetching account info...\n'));
  
  try {
    const profile = await getUserProfile();
    
    const username = profile.username || profile.user_name || credentials.username || 'Unknown';
    const phoneNumber = profile.phone_number || profile.phoneNumber || 'Unknown';
    const email = profile.email || 'Not available';
    
    console.log(chalk.gray('─────────────────────────────────────────────'));
    console.log(chalk.white('Username:     ') + chalk.cyan(username));
    console.log(chalk.white('Phone Number: ') + chalk.cyan(phoneNumber));
    if (email !== 'Not available') {
      console.log(chalk.white('Email:        ') + chalk.cyan(email));
    }
    console.log(chalk.gray('─────────────────────────────────────────────'));
    
    // Update stored credentials with username if we got it
    if (username && username !== 'Unknown' && username !== credentials.username) {
      await updateCredentials({ username });
      console.log(chalk.gray('\n(Updated cached username)'));
    }
    
    console.log(chalk.green('\n✅ Authentication working!\n'));
    
  } catch (error) {
    console.log(chalk.red('❌ Failed to fetch account info:'));
    console.log(chalk.red(`   ${error.message}`));
    
    if (error.message.includes('401') || error.message.includes('403')) {
      console.log(chalk.yellow('\n💡 Your session may have expired. Try running `textnow auth` again.\n'));
    } else {
      console.log(chalk.gray('\nCached credentials info:'));
      console.log(chalk.gray(`   Saved at: ${credentials.savedAt}`));
      if (credentials.username) {
        console.log(chalk.gray(`   Username: ${credentials.username}`));
      }
    }
    
    process.exit(1);
  }
}
