/**
 * Contact Form Email Service
 *
 * High-level functions for sending contact form related emails.
 */

import { sendEmail } from '../core';
import type { StaffContactNotificationData } from '../types';
import {
  createContactThankYouEmail,
  createStaffContactNotificationEmail,
} from '../templates/contact-templates';
import { logger } from '@/lib/logger';

/**
 * Send contact form thank you email to customer
 */
export async function sendContactThankYouEmail(
  email: string,
  name: string,
  topic: string,
  language: 'ar' | 'en'
): Promise<boolean> {
  const template = createContactThankYouEmail(name, topic, language);
  return sendEmail(email, template);
}

/**
 * Staff Contact Notification Data
 */

/**
 * Send contact form notification to staff
 */
export async function sendStaffContactNotification(
  data: StaffContactNotificationData
): Promise<boolean> {
  // Get staff notification emails from environment or use default
  const staffEmails = process.env.STAFF_NOTIFICATION_EMAIL || 'admin@mawidi.com';

  // Split by comma for multiple recipients
  const recipients = staffEmails.split(',').map(email => email.trim()).filter(Boolean);

  if (recipients.length === 0) {
    logger.warn('No staff notification email configured');
    return false;
  }

  const template = createStaffContactNotificationEmail(data);

  // Send to all recipients
  const results = await Promise.all(
    recipients.map(recipient => sendEmail(recipient, template))
  );

  const allSent = results.every(Boolean);

  if (allSent) {
    logger.info('Staff contact notification sent', {
      submissionId: data.submissionId,
      recipientCount: recipients.length
    });
  } else {
    logger.warn('Some staff contact notifications failed', {
      submissionId: data.submissionId,
      successCount: results.filter(Boolean).length,
      totalCount: recipients.length
    });
  }

  return allSent;
}
