import chalk from 'chalk';
import { loadCredentials } from '../lib/credentials.js';
import { sendMessage } from '../lib/api.js';

export async function sendCommand(phone, message) {
  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('\n📤 Sending message...\n'));
  console.log(chalk.gray('To: ') + chalk.white(phone));
  console.log(chalk.gray('Message: ') + chalk.white(message.substring(0, 50) + (message.length > 50 ? '...' : '')));
  
  try {
    const result = await sendMessage(phone, message);
    
    console.log(chalk.green('\n✅ Message sent successfully!'));
    
    if (result.id || result.message_id) {
      console.log(chalk.gray(`   Message ID: ${result.id || result.message_id}`));
    }
    
    console.log('');
    
  } catch (error) {
    console.log(chalk.red('\n❌ Failed to send message:'));
    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'));
    }
    
    process.exit(1);
  }
}
