import { Resend } from 'resend';
import * as dotenv from 'dotenv';

// Load environment variables
dotenv.config();

const resend = new Resend(process.env.RESEND_API_KEY);

async function testEmailSending() {
  console.log('🧪 Testing email sending configuration...\n');
  
  // Check environment variables
  console.log('📋 Environment Variables:');
  console.log('  RESEND_API_KEY:', process.env.RESEND_API_KEY ? `${process.env.RESEND_API_KEY.substring(0, 10)}...` : '❌ NOT SET');
  console.log('  RESEND_FROM_EMAIL:', process.env.RESEND_FROM_EMAIL || '❌ NOT SET');
  console.log('  NEXTAUTH_URL:', process.env.NEXTAUTH_URL || '❌ NOT SET');
  console.log('');
  
  if (!process.env.RESEND_API_KEY) {
    console.error('❌ RESEND_API_KEY is not set in .env file');
    process.exit(1);
  }
  
  if (!process.env.RESEND_FROM_EMAIL) {
    console.error('❌ RESEND_FROM_EMAIL is not set in .env file');
    process.exit(1);
  }
  
  // Clean up the from email (remove quotes and spaces)
  const fromEmail = process.env.RESEND_FROM_EMAIL.trim().replace(/^["']|["']$/g, '');
  console.log('📧 Using FROM email:', fromEmail);
  console.log('');
  
  // Test email sending
  console.log('📤 Attempting to send test email...');
  try {
    const result = await resend.emails.send({
      from: fromEmail,
      to: 'test@example.com', // This will fail but we'll see the error
      subject: 'Test Email',
      html: '<p>This is a test email</p>',
    });
    
    console.log('✅ Email API call successful!');
    console.log('Response:', JSON.stringify(result, null, 2));
  } catch (error: any) {
    console.error('❌ Error sending email:');
    console.error('  Message:', error.message);
    if (error.response) {
      console.error('  Response:', JSON.stringify(error.response, null, 2));
    }
    
    // Check for common errors
    if (error.message?.includes('domain')) {
      console.error('\n⚠️  Domain verification issue:');
      console.error('  The email domain needs to be verified in Resend dashboard');
      console.error('  For testing, use: onboarding@resend.dev');
    }
    
    if (error.message?.includes('unauthorized') || error.message?.includes('Invalid API key')) {
      console.error('\n⚠️  API Key issue:');
      console.error('  Check that your RESEND_API_KEY is correct');
      console.error('  Get a new key from: https://resend.com/api-keys');
    }
    
    process.exit(1);
  }
}

testEmailSending();







