/**
 * Interview Emails Service
 *
 * Business logic layer for interview-related email operations
 * Handles email sending with proper error handling and logging
 */

import {
  sendInterviewInvitationEmail,
  sendInterviewReminderEmail,
  sendInterviewCancellationEmail,
  sendEmail,
  createInterviewConfirmationEmail,
  InterviewDetails
} from '../email';

/**
 * Send interview invitation with booking link
 */
export async function sendInvitation(params: {
  email: string;
  applicantName: string;
  jobTitle: string;
  jobTitleAr: string;
  bookingToken: string;
  expiresAt: Date;
  language: 'ar' | 'en';
}): Promise<{ success: boolean; error?: string }> {
  try {
    const expiryDate = params.expiresAt.toLocaleDateString(
      params.language === 'ar' ? 'ar-SA' : 'en-US',
      { year: 'numeric', month: 'long', day: 'numeric' }
    );

    const sent = await sendInterviewInvitationEmail(
      params.email,
      params.applicantName,
      params.jobTitle,
      params.jobTitleAr,
      params.bookingToken,
      expiryDate,
      params.language
    );

    if (!sent) {
      return { success: false, error: 'Failed to send email' };
    }

    console.log(`[Interview] Invitation sent to ${params.email}`);
    return { success: true };
  } catch (error) {
    console.error('[Interview] Failed to send invitation:', error);
    return { success: false, error: 'Internal error sending email' };
  }
}

/**
 * Send interview confirmation with meeting details
 */
export async function sendConfirmation(params: {
  email: string;
  details: InterviewDetails;
}): Promise<{ success: boolean; error?: string }> {
  try {
    const template = createInterviewConfirmationEmail(params.details);
    const sent = await sendEmail(params.email, template);

    if (!sent) {
      return { success: false, error: 'Failed to send email' };
    }

    console.log(`[Interview] Confirmation sent to ${params.email}`);
    return { success: true };
  } catch (error) {
    console.error('[Interview] Failed to send confirmation:', error);
    return { success: false, error: 'Internal error sending email' };
  }
}

/**
 * Send interview reminder (typically 24 hours before)
 */
export async function sendReminder(params: {
  email: string;
  details: Omit<InterviewDetails, 'preparationInstructions'>;
}): Promise<{ success: boolean; error?: string }> {
  try {
    const sent = await sendInterviewReminderEmail(params.email, params.details);

    if (!sent) {
      return { success: false, error: 'Failed to send email' };
    }

    console.log(`[Interview] Reminder sent to ${params.email}`);
    return { success: true };
  } catch (error) {
    console.error('[Interview] Failed to send reminder:', error);
    return { success: false, error: 'Internal error sending email' };
  }
}

/**
 * Send interview cancellation notification
 */
export async function sendCancellation(params: {
  email: string;
  applicantName: string;
  jobTitle: string;
  jobTitleAr: string;
  reason: string;
  rescheduleOption: boolean;
  language: 'ar' | 'en';
}): Promise<{ success: boolean; error?: string }> {
  try {
    const sent = await sendInterviewCancellationEmail(
      params.email,
      params.applicantName,
      params.jobTitle,
      params.jobTitleAr,
      params.reason,
      params.rescheduleOption,
      params.language
    );

    if (!sent) {
      return { success: false, error: 'Failed to send email' };
    }

    console.log(`[Interview] Cancellation sent to ${params.email}`);
    return { success: true };
  } catch (error) {
    console.error('[Interview] Failed to send cancellation:', error);
    return { success: false, error: 'Internal error sending email' };
  }
}

/**
 * Generate calendar invite (.ics) file content
 *
 * This follows the iCalendar format (RFC 5545)
 * Compatible with Google Calendar, Outlook, Apple Calendar, etc.
 */
export function generateCalendarInvite(params: {
  applicantName: string;
  applicantEmail: string;
  jobTitle: string;
  confirmedDate: Date;
  durationMinutes: number;
  timezone: string;
  meetingLink?: string;
  meetingPlatform?: string;
  language: 'ar' | 'en';
}): string {
  const {
    applicantName,
    applicantEmail,
    jobTitle,
    confirmedDate,
    durationMinutes,
    timezone,
    meetingLink,
    meetingPlatform,
    language
  } = params;

  const isArabic = language === 'ar';

  // Calculate end time
  const endDate = new Date(confirmedDate.getTime() + durationMinutes * 60000);

  // Format dates to iCalendar format (YYYYMMDDTHHMMSS)
  const formatICalDate = (date: Date): string => {
    return date.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
  };

  const startDateTime = formatICalDate(confirmedDate);
  const endDateTime = formatICalDate(endDate);
  const now = formatICalDate(new Date());

  // Create unique ID
  const uid = `interview-${Date.now()}@mawidi.com`;

  // Build description
  const description = isArabic
    ? `مقابلة وظيفية لمنصب ${jobTitle}\\n\\n` +
      `المرشح: ${applicantName}\\n` +
      `البريد الإلكتروني: ${applicantEmail}\\n` +
      (meetingLink ? `\\nرابط الاجتماع: ${meetingLink}\\n` : '') +
      `\\nمنصة الاجتماع: ${meetingPlatform || 'غير محدد'}\\n` +
      `\\nيرجى الانضمام قبل 5 دقائق من الموعد المحدد.`
    : `Job interview for ${jobTitle} position\\n\\n` +
      `Candidate: ${applicantName}\\n` +
      `Email: ${applicantEmail}\\n` +
      (meetingLink ? `\\nMeeting Link: ${meetingLink}\\n` : '') +
      `\\nMeeting Platform: ${meetingPlatform || 'TBD'}\\n` +
      `\\nPlease join 5 minutes before the scheduled time.`;

  const summary = isArabic
    ? `مقابلة: ${jobTitle} - ${applicantName}`
    : `Interview: ${jobTitle} - ${applicantName}`;

  // Build .ics content
  const icsContent = [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//Mawidi//Interview Scheduler//EN',
    'CALSCALE:GREGORIAN',
    'METHOD:REQUEST',
    'BEGIN:VEVENT',
    `UID:${uid}`,
    `DTSTAMP:${now}`,
    `DTSTART:${startDateTime}`,
    `DTEND:${endDateTime}`,
    `SUMMARY:${summary}`,
    `DESCRIPTION:${description}`,
    `LOCATION:${meetingLink || (isArabic ? 'سيتم إرسال رابط الاجتماع' : 'Meeting link to be provided')}`,
    'STATUS:CONFIRMED',
    'SEQUENCE:0',
    `ORGANIZER;CN=Mawidi HR:mailto:careers@mawidi.com`,
    `ATTENDEE;CN=${applicantName};RSVP=TRUE:mailto:${applicantEmail}`,
    'BEGIN:VALARM',
    'TRIGGER:-PT15M',
    'ACTION:DISPLAY',
    `DESCRIPTION:${isArabic ? 'تذكير: مقابلتك خلال 15 دقيقة' : 'Reminder: Your interview starts in 15 minutes'}`,
    'END:VALARM',
    'END:VEVENT',
    'END:VCALENDAR'
  ].join('\r\n');

  return icsContent;
}

/**
 * Example usage:
 *
 * ```typescript
 * // 1. Send invitation when candidate is selected
 * import * as interviewEmails from '@/lib/services/interview-emails.service';
 *
 * const result = await interviewEmails.sendInvitation({
 *   email: 'candidate@example.com',
 *   applicantName: 'John Doe',
 *   jobTitle: 'Senior Developer',
 *   jobTitleAr: 'مطور أول',
 *   bookingToken: 'abc123xyz',
 *   expiresAt: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), // 3 days
 *   language: 'en'
 * });
 *
 * // 2. Send confirmation when staff confirms interview
 * await interviewEmails.sendConfirmation({
 *   email: 'candidate@example.com',
 *   details: {
 *     applicantName: 'John Doe',
 *     jobTitle: 'Senior Developer',
 *     jobTitleAr: 'مطور أول',
 *     confirmedDate: 'Monday, January 15, 2025',
 *     confirmedTime: '10:00 AM',
 *     timezone: 'Asia/Qatar',
 *     meetingLink: 'https://meet.google.com/abc-defg-hij',
 *     meetingPlatform: 'google_meet',
 *     language: 'en'
 *   }
 * });
 *
 * // 3. Generate calendar invite
 * const icsContent = interviewEmails.generateCalendarInvite({
 *   applicantName: 'John Doe',
 *   applicantEmail: 'candidate@example.com',
 *   jobTitle: 'Senior Developer',
 *   confirmedDate: new Date('2025-01-15T10:00:00Z'),
 *   durationMinutes: 60,
 *   timezone: 'Asia/Qatar',
 *   meetingLink: 'https://meet.google.com/abc-defg-hij',
 *   meetingPlatform: 'Google Meet',
 *   language: 'en'
 * });
 *
 * // Save or send as attachment
 * fs.writeFileSync('interview.ics', icsContent);
 * ```
 */
