/**
 * SKILL: Send Bilingual Email
 *
 * Send email in both Arabic and English, or in user's preferred language.
 * Automatically handles template selection, rendering, and sending.
 *
 * Token Savings: 8,000+ (template rendering + dual send → single skill call)
 *
 * Use this skill when:
 * - Sending welcome emails
 * - Sending confirmation emails
 * - Sending notification emails
 * - User's language preference is unknown
 */

import * as email from "../servers/email";

export interface BilingualEmailInput {
  to: string;
  template: "otp" | "welcome" | "password-reset" | "demo-confirmation";
  data: Record<string, any>;
  preferredLanguage?: "ar" | "en";
  sendBoth?: boolean; // Send in both languages
}

export interface BilingualEmailResult {
  success: boolean;
  sent: {
    ar?: { success: boolean; messageId?: string };
    en?: { success: boolean; messageId?: string };
  };
  error?: string;
}

/**
 * Send email in one or both languages based on preferences.
 *
 * @param input - Email data and language preferences
 * @returns Send results for each language
 *
 * @example
 * ```typescript
 * // Send welcome email in user's preferred language (Arabic)
 * const result = await sendBilingualEmail({
 *   to: 'user@example.com',
 *   template: 'welcome',
 *   data: {
 *     name: 'أحمد محمد',
 *     companyName: 'عيادة الأمل'
 *   },
 *   preferredLanguage: 'ar'
 * });
 *
 * console.log(result.success ? '✓ Welcome email sent' : '✗ Failed');
 * ```
 *
 * @example
 * ```typescript
 * // Send demo confirmation in both languages
 * const result = await sendBilingualEmail({
 *   to: 'prospect@example.com',
 *   template: 'demo-confirmation',
 *   data: {
 *     customerName: 'John Doe',
 *     service: 'Dental Consultation',
 *     date: '2025-11-20',
 *     time: '10:00'
 *   },
 *   sendBoth: true
 * });
 *
 * console.log('Sent in both languages:');
 * console.log(`  Arabic: ${result.sent.ar?.success ? '✓' : '✗'}`);
 * console.log(`  English: ${result.sent.en?.success ? '✓' : '✗'}`);
 * ```
 *
 * @example
 * ```typescript
 * // Send OTP with automatic language detection from user data
 * import * as users from '../servers/database/users';
 *
 * const user = await users.getUserByEmail('user@example.com');
 * const language = user?.location?.startsWith('ar') ? 'ar' : 'en';
 *
 * await sendBilingualEmail({
 *   to: user.email,
 *   template: 'otp',
 *   data: {
 *     otp: '123456',
 *     name: user.name
 *   },
 *   preferredLanguage: language
 * });
 * ```
 */
export async function sendBilingualEmail(
  input: BilingualEmailInput,
): Promise<BilingualEmailResult> {
  const result: BilingualEmailResult = {
    success: false,
    sent: {},
  };

  try {
    if (input.sendBoth) {
      // Send in both languages
      const [arResult, enResult] = await Promise.all([
        email.sendTemplateEmail({
          to: input.to,
          template: input.template,
          language: "ar",
          data: input.data,
        }),
        email.sendTemplateEmail({
          to: input.to,
          template: input.template,
          language: "en",
          data: input.data,
        }),
      ]);

      result.sent.ar = arResult;
      result.sent.en = enResult;
      result.success = arResult.success || enResult.success;
    } else {
      // Send in preferred language (default to English)
      const language = input.preferredLanguage || "en";
      const sendResult = await email.sendTemplateEmail({
        to: input.to,
        template: input.template,
        language,
        data: input.data,
      });

      result.sent[language] = sendResult;
      result.success = sendResult.success;
    }

    return result;
  } catch (error: any) {
    return {
      success: false,
      sent: {},
      error: error.message,
    };
  }
}

/**
 * Send welcome email after user registration.
 *
 * @param userEmail - User email
 * @param userName - User name
 * @param companyName - Company name
 * @param language - Preferred language
 * @returns Send result
 *
 * @example
 * ```typescript
 * await sendWelcomeEmail(
 *   'user@example.com',
 *   'John Doe',
 *   'Acme Corp',
 *   'en'
 * );
 * ```
 */
export async function sendWelcomeEmail(
  userEmail: string,
  userName: string,
  companyName: string,
  language: "ar" | "en" = "en",
): Promise<BilingualEmailResult> {
  return sendBilingualEmail({
    to: userEmail,
    template: "welcome",
    data: { name: userName, companyName },
    preferredLanguage: language,
  });
}

/**
 * Send OTP email.
 *
 * @param userEmail - User email
 * @param otp - OTP code
 * @param purpose - OTP purpose
 * @param language - Preferred language
 * @returns Send result
 *
 * @example
 * ```typescript
 * await sendOTPEmail('user@example.com', '123456', 'signup', 'ar');
 * ```
 */
export async function sendOTPEmail(
  userEmail: string,
  otp: string,
  purpose: "signup" | "password-reset" | "verification",
  language: "ar" | "en" = "en",
): Promise<BilingualEmailResult> {
  return sendBilingualEmail({
    to: userEmail,
    template: "otp",
    data: { otp, purpose },
    preferredLanguage: language,
  });
}

export default {
  sendBilingualEmail,
  sendWelcomeEmail,
  sendOTPEmail,
};
