import chalk from 'chalk';
import { promises as fs } from 'fs';
import path from 'path';
import { loadCredentials } from '../lib/credentials.js';
import { sendImage } from '../lib/api.js';

export async function sendImageCommand(phone, imagePath, options) {
  const credentials = await loadCredentials();
  
  if (!credentials) {
    console.log(chalk.red('\n❌ Not authenticated. Run `textnow auth` first.\n'));
    process.exit(1);
  }
  
  // Check if file exists
  const absolutePath = path.resolve(imagePath);
  try {
    await fs.access(absolutePath);
  } catch {
    console.log(chalk.red(`\n❌ Image file not found: ${absolutePath}\n`));
    process.exit(1);
  }
  
  const caption = options.caption || '';
  
  console.log(chalk.cyan('\n📤 Sending image...\n'));
  console.log(chalk.gray('To: ') + chalk.white(phone));
  console.log(chalk.gray('Image: ') + chalk.white(path.basename(imagePath)));
  if (caption) {
    console.log(chalk.gray('Caption: ') + chalk.white(caption.substring(0, 50) + (caption.length > 50 ? '...' : '')));
  }
  
  try {
    const result = await sendImage(phone, imagePath, caption);
    
    console.log(chalk.green('\n✅ Image 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 image:'));
    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);
  }
}
