#!/usr/bin/env node

/**
 * Test Interview Email Templates
 *
 * Usage:
 *   node scripts/test-interview-emails.mjs invitation
 *   node scripts/test-interview-emails.mjs confirmation
 *   node scripts/test-interview-emails.mjs reminder
 *   node scripts/test-interview-emails.mjs cancellation
 *   node scripts/test-interview-emails.mjs calendar
 *   node scripts/test-interview-emails.mjs all
 */

import {
  sendInterviewInvitationEmail,
  sendInterviewReminderEmail,
  sendInterviewCancellationEmail,
  sendEmail,
  createInterviewConfirmationEmail
} from '../lib/email.ts';
import { generateCalendarInvite } from '../lib/services/interview-emails.service.ts';
import fs from 'fs';

const TEST_EMAIL = 'test@example.com';
const TEST_NAME = 'Ahmed Mohamed';
const TEST_JOB_TITLE = 'Senior Full-Stack Developer';
const TEST_JOB_TITLE_AR = 'مطور ويب متقدم';

async function testInvitation(language = 'en') {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`Testing Interview Invitation Email (${language.toUpperCase()})`);
  console.log('='.repeat(60));

  const expiryDate = new Date();
  expiryDate.setDate(expiryDate.getDate() + 3); // 3 days from now

  const formattedDate = expiryDate.toLocaleDateString(
    language === 'ar' ? 'ar-SA' : 'en-US',
    { year: 'numeric', month: 'long', day: 'numeric' }
  );

  const result = await sendInterviewInvitationEmail(
    TEST_EMAIL,
    TEST_NAME,
    TEST_JOB_TITLE,
    TEST_JOB_TITLE_AR,
    'test-token-abc123xyz456',
    formattedDate,
    language
  );

  if (result) {
    console.log('✅ Invitation email sent successfully');
    console.log(`📧 Check MailHog at http://localhost:8025`);
  } else {
    console.log('❌ Failed to send invitation email');
  }
}

async function testConfirmation(language = 'en') {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`Testing Interview Confirmation Email (${language.toUpperCase()})`);
  console.log('='.repeat(60));

  const confirmedDate = new Date();
  confirmedDate.setDate(confirmedDate.getDate() + 7); // 7 days from now

  const formattedDate = confirmedDate.toLocaleDateString(
    language === 'ar' ? 'ar-SA' : 'en-US',
    { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }
  );

  const details = {
    applicantName: TEST_NAME,
    jobTitle: TEST_JOB_TITLE,
    jobTitleAr: TEST_JOB_TITLE_AR,
    confirmedDate: formattedDate,
    confirmedTime: '10:00 AM',
    timezone: 'Asia/Qatar (GMT+3)',
    meetingLink: 'https://meet.google.com/abc-defg-hij',
    meetingPlatform: 'google_meet',
    meetingId: 'abc-defg-hij',
    meetingPassword: undefined,
    preparationInstructions: undefined, // Will use default
    language: language
  };

  const template = createInterviewConfirmationEmail(details);
  const result = await sendEmail(TEST_EMAIL, template);

  if (result) {
    console.log('✅ Confirmation email sent successfully');
    console.log(`📧 Check MailHog at http://localhost:8025`);
  } else {
    console.log('❌ Failed to send confirmation email');
  }
}

async function testReminder(language = 'en') {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`Testing Interview Reminder Email (${language.toUpperCase()})`);
  console.log('='.repeat(60));

  const tomorrowDate = new Date();
  tomorrowDate.setDate(tomorrowDate.getDate() + 1); // tomorrow

  const formattedDate = tomorrowDate.toLocaleDateString(
    language === 'ar' ? 'ar-SA' : 'en-US',
    { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }
  );

  const details = {
    applicantName: TEST_NAME,
    jobTitle: TEST_JOB_TITLE,
    jobTitleAr: TEST_JOB_TITLE_AR,
    confirmedDate: formattedDate,
    confirmedTime: '10:00 AM',
    timezone: 'Asia/Qatar (GMT+3)',
    meetingLink: 'https://meet.google.com/abc-defg-hij',
    meetingPlatform: 'google_meet',
    meetingId: 'abc-defg-hij',
    meetingPassword: '123456',
    language: language
  };

  const result = await sendInterviewReminderEmail(TEST_EMAIL, details);

  if (result) {
    console.log('✅ Reminder email sent successfully');
    console.log(`📧 Check MailHog at http://localhost:8025`);
  } else {
    console.log('❌ Failed to send reminder email');
  }
}

async function testCancellation(language = 'en') {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`Testing Interview Cancellation Email (${language.toUpperCase()})`);
  console.log('='.repeat(60));

  const reason = language === 'ar'
    ? 'نعتذر، ولكن تم ملء الوظيفة بمرشح آخر. نحن معجبون جداً بمؤهلاتك ونود أن نحتفظ بسيرتك الذاتية للفرص المستقبلية.'
    : 'We apologize, but the position has been filled with another candidate. We were very impressed with your qualifications and would like to keep your resume on file for future opportunities.';

  const result = await sendInterviewCancellationEmail(
    TEST_EMAIL,
    TEST_NAME,
    TEST_JOB_TITLE,
    TEST_JOB_TITLE_AR,
    reason,
    false, // No reschedule option
    language
  );

  if (result) {
    console.log('✅ Cancellation email sent successfully');
    console.log(`📧 Check MailHog at http://localhost:8025`);
  } else {
    console.log('❌ Failed to send cancellation email');
  }
}

async function testCalendarInvite(language = 'en') {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`Testing Calendar Invite Generation (${language.toUpperCase()})`);
  console.log('='.repeat(60));

  const interviewDate = new Date();
  interviewDate.setDate(interviewDate.getDate() + 7); // 7 days from now
  interviewDate.setHours(10, 0, 0, 0); // 10:00 AM

  const icsContent = generateCalendarInvite({
    applicantName: TEST_NAME,
    applicantEmail: TEST_EMAIL,
    jobTitle: TEST_JOB_TITLE,
    confirmedDate: interviewDate,
    durationMinutes: 60,
    timezone: 'Asia/Qatar',
    meetingLink: 'https://meet.google.com/abc-defg-hij',
    meetingPlatform: 'Google Meet',
    language: language
  });

  const filename = `interview-invite-${language}.ics`;
  fs.writeFileSync(filename, icsContent);

  console.log(`✅ Calendar invite generated successfully`);
  console.log(`📅 File saved: ${filename}`);
  console.log(`\nPreview:\n${'-'.repeat(60)}`);
  console.log(icsContent.substring(0, 500) + '...');
  console.log('-'.repeat(60));
}

// Main execution
const command = process.argv[2] || 'all';
const language = process.argv[3] || 'en';

console.log('\n🚀 Interview Email Templates Test Suite');
console.log(`Language: ${language.toUpperCase()}`);

(async () => {
  try {
    switch (command) {
      case 'invitation':
        await testInvitation(language);
        break;
      case 'confirmation':
        await testConfirmation(language);
        break;
      case 'reminder':
        await testReminder(language);
        break;
      case 'cancellation':
        await testCancellation(language);
        break;
      case 'calendar':
        await testCalendarInvite(language);
        break;
      case 'all':
        await testInvitation(language);
        await testConfirmation(language);
        await testReminder(language);
        await testCancellation(language);
        await testCalendarInvite(language);
        break;
      default:
        console.error(`\n❌ Unknown command: ${command}`);
        console.log('\nUsage:');
        console.log('  node scripts/test-interview-emails.mjs <command> [language]');
        console.log('\nCommands:');
        console.log('  invitation    - Test invitation email');
        console.log('  confirmation  - Test confirmation email');
        console.log('  reminder      - Test reminder email');
        console.log('  cancellation  - Test cancellation email');
        console.log('  calendar      - Test calendar invite generation');
        console.log('  all           - Test all emails (default)');
        console.log('\nLanguages: en (default), ar');
        process.exit(1);
    }

    console.log(`\n${'='.repeat(60)}`);
    console.log('✅ Test completed successfully!');
    console.log('='.repeat(60));
    console.log('\nNext steps:');
    console.log('1. Check MailHog at http://localhost:8025 to view emails');
    console.log('2. Open generated .ics files to test calendar integration');
    console.log('3. Verify both Arabic (RTL) and English (LTR) layouts');
    console.log('\n');

  } catch (error) {
    console.error('\n❌ Test failed:', error);
    process.exit(1);
  }
})();
