/**
 * Real Estate WhatsApp Message Templates Service
 *
 * Pure formatting functions that produce WhatsApp-friendly plain text messages
 * with emoji and WhatsApp markdown (*bold*, _italic_, ~strikethrough~).
 * Supports English and Arabic (RTL-friendly with Arabic comma).
 *
 * These functions are stateless and have no side effects -- they simply accept
 * data and return a formatted string. The notification service or WhatsApp
 * service calls these to build message bodies before sending.
 *
 * @module lib/services/real-estate/whatsapp-templates.service
 */

// ═══════════════════════════════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════════════════════════════

/** Format a number as a locale-aware price string. */
function formatPrice(amount: number, currency: string, language: 'en' | 'ar'): string {
  const locale = language === 'ar' ? 'ar-QA' : 'en-QA';
  const formatted = amount.toLocaleString(locale);
  return language === 'ar' ? `${formatted} ${currency}` : `${currency} ${formatted}`;
}

/** Arabic comma for list separation in AR messages. */
const AR_COMMA = '\u060C';

/** Footer line for all messages. */
function footer(language: 'en' | 'ar'): string {
  return language === 'ar' ? '_\u0628\u0648\u0627\u0633\u0637\u0629 \u0645\u0627\u0648\u062F\u064A_' : '_Powered by Mawidi_';
}

// ═══════════════════════════════════════════════════════════════════════
// 1. Viewing Confirmation
// ═══════════════════════════════════════════════════════════════════════

export function formatViewingConfirmation(
  data: {
    clientName: string;
    propertyTitle: string;
    propertyAddress: string;
    viewingDate: string;
    viewingTime: string;
    brokerName: string;
    brokerPhone: string;
    mapUrl?: string | null;
    viewingType: string;
    meetingLink?: string | null;
  },
  language: 'en' | 'ar',
): string {
  if (language === 'ar') {
    const lines: string[] = [
      '\u2705 *\u062A\u0623\u0643\u064A\u062F \u0627\u0644\u0645\u0639\u0627\u064A\u0646\u0629*',
      '',
      `\u0645\u0631\u062D\u0628\u0627\u064B ${data.clientName}!`,
      '',
      '\u062A\u0645 \u062D\u062C\u0632 \u0645\u0639\u0627\u064A\u0646\u0629 \u0627\u0644\u0639\u0642\u0627\u0631:',
      '',
      `\uD83C\uDFE0 ${data.propertyTitle}`,
      `\uD83D\uDCCD ${data.propertyAddress}`,
      `\uD83D\uDCC5 ${data.viewingDate} \u0627\u0644\u0633\u0627\u0639\u0629 ${data.viewingTime}`,
      `\uD83D\uDC64 \u0627\u0644\u0648\u0633\u064A\u0637: ${data.brokerName}`,
      `\uD83D\uDCDE ${data.brokerPhone}`,
    ];

    if (data.viewingType === 'VIRTUAL' && data.meetingLink) {
      lines.push(`\uD83D\uDCBB \u0631\u0627\u0628\u0637 \u0627\u0644\u0627\u062C\u062A\u0645\u0627\u0639: ${data.meetingLink}`);
    }

    if (data.mapUrl) {
      lines.push(`\uD83D\uDDFA\uFE0F \u0627\u0644\u062E\u0631\u064A\u0637\u0629: ${data.mapUrl}`);
    }

    lines.push('');
    lines.push('\u0627\u0644\u0631\u062C\u0627\u0621 \u0627\u0644\u062D\u0636\u0648\u0631 \u0642\u0628\u0644 \u0627\u0644\u0645\u0648\u0639\u062F \u0628\u0640 5 \u062F\u0642\u0627\u0626\u0642. \u0625\u0630\u0627 \u0643\u0646\u062A \u062A\u0631\u063A\u0628 \u0641\u064A \u0625\u0639\u0627\u062F\u0629 \u0627\u0644\u062C\u062F\u0648\u0644\u0629' + AR_COMMA + ' \u0631\u062F \u0639\u0644\u0649 \u0647\u0630\u0647 \u0627\u0644\u0631\u0633\u0627\u0644\u0629.');
    lines.push('');
    lines.push(footer('ar'));

    return lines.join('\n');
  }

  // English
  const lines: string[] = [
    '\u2705 *Viewing Confirmed*',
    '',
    `Hi ${data.clientName}!`,
    '',
    'Your property viewing has been scheduled:',
    '',
    `\uD83C\uDFE0 ${data.propertyTitle}`,
    `\uD83D\uDCCD ${data.propertyAddress}`,
    `\uD83D\uDCC5 ${data.viewingDate} at ${data.viewingTime}`,
    `\uD83D\uDC64 Broker: ${data.brokerName}`,
    `\uD83D\uDCDE ${data.brokerPhone}`,
  ];

  if (data.viewingType === 'VIRTUAL' && data.meetingLink) {
    lines.push(`\uD83D\uDCBB Meeting link: ${data.meetingLink}`);
  }

  if (data.mapUrl) {
    lines.push(`\uD83D\uDDFA\uFE0F Map: ${data.mapUrl}`);
  }

  lines.push('');
  lines.push('Please arrive 5 minutes early. If you need to reschedule, reply to this message.');
  lines.push('');
  lines.push(footer('en'));

  return lines.join('\n');
}

// ═══════════════════════════════════════════════════════════════════════
// 2. Viewing Reminder
// ═══════════════════════════════════════════════════════════════════════

export function formatViewingReminder(
  data: {
    clientName: string;
    propertyTitle: string;
    propertyAddress: string;
    viewingDate: string;
    viewingTime: string;
    brokerName: string;
    brokerPhone: string;
    mapUrl?: string | null;
    reminderType: '24h' | '2h';
  },
  language: 'en' | 'ar',
): string {
  if (language === 'ar') {
    const heading =
      data.reminderType === '24h'
        ? '\u23F0 *\u062A\u0630\u0643\u064A\u0631 \u0628\u0627\u0644\u0645\u0639\u0627\u064A\u0646\u0629 - \u063A\u062F\u0627\u064B*'
        : '\u23F0 *\u0645\u0639\u0627\u064A\u0646\u062A\u0643 \u0628\u0639\u062F \u0633\u0627\u0639\u062A\u064A\u0646*';

    const timeNote =
      data.reminderType === '24h'
        ? `\uD83D\uDCC5 \u063A\u062F\u0627\u064B ${data.viewingDate} \u0627\u0644\u0633\u0627\u0639\u0629 ${data.viewingTime}`
        : `\uD83D\uDCC5 \u0627\u0644\u064A\u0648\u0645 \u0627\u0644\u0633\u0627\u0639\u0629 ${data.viewingTime}`;

    const lines: string[] = [
      heading,
      '',
      `\u0645\u0631\u062D\u0628\u0627\u064B ${data.clientName}${AR_COMMA}`,
      '',
      `\uD83C\uDFE0 ${data.propertyTitle}`,
      `\uD83D\uDCCD ${data.propertyAddress}`,
      timeNote,
      `\uD83D\uDC64 \u0627\u0644\u0648\u0633\u064A\u0637: ${data.brokerName}`,
      `\uD83D\uDCDE ${data.brokerPhone}`,
    ];

    if (data.mapUrl) {
      lines.push(`\uD83D\uDDFA\uFE0F \u0627\u0644\u062E\u0631\u064A\u0637\u0629: ${data.mapUrl}`);
    }

    lines.push('');
    lines.push(data.reminderType === '2h' ? '\u0646\u0631\u0627\u0643 \u0642\u0631\u064A\u0628\u0627\u064B!' : '\u0644\u0627 \u062A\u0646\u0633 \u0645\u0648\u0639\u062F\u0643!');
    lines.push('');
    lines.push(footer('ar'));

    return lines.join('\n');
  }

  // English
  const heading =
    data.reminderType === '24h'
      ? '\u23F0 *Viewing Reminder - Tomorrow*'
      : '\u23F0 *Your Viewing is in 2 Hours*';

  const timeNote =
    data.reminderType === '24h'
      ? `\uD83D\uDCC5 Tomorrow, ${data.viewingDate} at ${data.viewingTime}`
      : `\uD83D\uDCC5 Today at ${data.viewingTime}`;

  const lines: string[] = [
    heading,
    '',
    `Hi ${data.clientName},`,
    '',
    `\uD83C\uDFE0 ${data.propertyTitle}`,
    `\uD83D\uDCCD ${data.propertyAddress}`,
    timeNote,
    `\uD83D\uDC64 Broker: ${data.brokerName}`,
    `\uD83D\uDCDE ${data.brokerPhone}`,
  ];

  if (data.mapUrl) {
    lines.push(`\uD83D\uDDFA\uFE0F Map: ${data.mapUrl}`);
  }

  lines.push('');
  lines.push(data.reminderType === '2h' ? 'See you soon!' : "Don't forget your appointment!");
  lines.push('');
  lines.push(footer('en'));

  return lines.join('\n');
}

// ═══════════════════════════════════════════════════════════════════════
// 3. Post-Viewing Follow-Up
// ═══════════════════════════════════════════════════════════════════════

export function formatPostViewingFollowUp(
  data: {
    clientName: string;
    propertyTitle: string;
    agencyName: string;
  },
  language: 'en' | 'ar',
): string {
  if (language === 'ar') {
    return [
      `\uD83C\uDFE0 *\u0645\u062A\u0627\u0628\u0639\u0629 \u0628\u0639\u062F \u0627\u0644\u0645\u0639\u0627\u064A\u0646\u0629*`,
      '',
      `\u0645\u0631\u062D\u0628\u0627\u064B ${data.clientName}${AR_COMMA}`,
      '',
      `\u0634\u0643\u0631\u0627\u064B \u0644\u0632\u064A\u0627\u0631\u062A\u0643 *${data.propertyTitle}*!`,
      '',
      '\u0646\u0648\u062F \u0633\u0645\u0627\u0639 \u0631\u0623\u064A\u0643. \u0647\u0644 \u062A\u0631\u063A\u0628 \u0641\u064A:',
      `\u2022 \u062D\u062C\u0632 \u0645\u0639\u0627\u064A\u0646\u0629 \u062B\u0627\u0646\u064A\u0629`,
      `\u2022 \u062A\u0642\u062F\u064A\u0645 \u0639\u0631\u0636`,
      `\u2022 \u0639\u0631\u0636 \u0639\u0642\u0627\u0631\u0627\u062A \u0645\u0634\u0627\u0628\u0647\u0629`,
      '',
      `\u0631\u062F \u0639\u0644\u0649 \u0647\u0630\u0647 \u0627\u0644\u0631\u0633\u0627\u0644\u0629 \u0644\u0625\u0639\u0644\u0627\u0645\u0646\u0627!`,
      '',
      `${data.agencyName}`,
      footer('ar'),
    ].join('\n');
  }

  return [
    `\uD83C\uDFE0 *Post-Viewing Follow-Up*`,
    '',
    `Hi ${data.clientName},`,
    '',
    `Thank you for visiting *${data.propertyTitle}*!`,
    '',
    "We'd love to hear your thoughts. Would you like to:",
    '\u2022 Schedule a second viewing',
    '\u2022 Make an offer',
    '\u2022 See similar properties',
    '',
    'Reply to let us know!',
    '',
    `${data.agencyName}`,
    footer('en'),
  ].join('\n');
}

// ═══════════════════════════════════════════════════════════════════════
// 4. Viewing Cancellation
// ═══════════════════════════════════════════════════════════════════════

export function formatViewingCancellation(
  data: {
    clientName: string;
    propertyTitle: string;
    viewingDate: string;
    viewingTime: string;
    reason?: string;
  },
  language: 'en' | 'ar',
): string {
  if (language === 'ar') {
    const lines: string[] = [
      '\u274C *\u0625\u0644\u063A\u0627\u0621 \u0627\u0644\u0645\u0639\u0627\u064A\u0646\u0629*',
      '',
      `\u0645\u0631\u062D\u0628\u0627\u064B ${data.clientName}${AR_COMMA}`,
      '',
      '\u062A\u0645 \u0625\u0644\u063A\u0627\u0621 \u0645\u0639\u0627\u064A\u0646\u0629 \u0627\u0644\u0639\u0642\u0627\u0631 \u0627\u0644\u062A\u0627\u0644\u064A\u0629:',
      '',
      `\uD83C\uDFE0 ${data.propertyTitle}`,
      `\uD83D\uDCC5 ${data.viewingDate} \u0627\u0644\u0633\u0627\u0639\u0629 ${data.viewingTime}`,
    ];

    if (data.reason) {
      lines.push(`\uD83D\uDCDD \u0627\u0644\u0633\u0628\u0628: ${data.reason}`);
    }

    lines.push('');
    lines.push(`\u0625\u0630\u0627 \u0643\u0646\u062A \u062A\u0631\u063A\u0628 \u0641\u064A \u0625\u0639\u0627\u062F\u0629 \u0627\u0644\u062C\u062F\u0648\u0644\u0629${AR_COMMA} \u0631\u062F \u0639\u0644\u0649 \u0647\u0630\u0647 \u0627\u0644\u0631\u0633\u0627\u0644\u0629.`);
    lines.push('');
    lines.push(footer('ar'));

    return lines.join('\n');
  }

  // English
  const lines: string[] = [
    '\u274C *Viewing Cancelled*',
    '',
    `Hi ${data.clientName},`,
    '',
    'The following property viewing has been cancelled:',
    '',
    `\uD83C\uDFE0 ${data.propertyTitle}`,
    `\uD83D\uDCC5 ${data.viewingDate} at ${data.viewingTime}`,
  ];

  if (data.reason) {
    lines.push(`\uD83D\uDCDD Reason: ${data.reason}`);
  }

  lines.push('');
  lines.push('If you would like to reschedule, reply to this message.');
  lines.push('');
  lines.push(footer('en'));

  return lines.join('\n');
}

// ═══════════════════════════════════════════════════════════════════════
// 5. Price Drop Alert
// ═══════════════════════════════════════════════════════════════════════

export function formatPriceDropAlert(
  data: {
    clientName: string;
    propertyTitle: string;
    propertyAddress: string;
    oldPrice: number;
    newPrice: number;
    currency: string;
    dropPercentage: number;
  },
  language: 'en' | 'ar',
): string {
  const pctText = `${Math.round(data.dropPercentage)}%`;

  if (language === 'ar') {
    const oldFormatted = formatPrice(data.oldPrice, data.currency, 'ar');
    const newFormatted = formatPrice(data.newPrice, data.currency, 'ar');

    return [
      `\uD83D\uDCB0 *\u062A\u0646\u0628\u064A\u0647 \u0627\u0646\u062E\u0641\u0627\u0636 \u0627\u0644\u0633\u0639\u0631*`,
      '',
      `\u0645\u0631\u062D\u0628\u0627\u064B ${data.clientName}${AR_COMMA}`,
      '',
      `\u0627\u0646\u062E\u0641\u0636 \u0633\u0639\u0631 \u0639\u0642\u0627\u0631 \u0643\u0646\u062A \u0645\u0647\u062A\u0645\u0627\u064B \u0628\u0647:`,
      '',
      `\uD83C\uDFE0 ${data.propertyTitle}`,
      `\uD83D\uDCCD ${data.propertyAddress}`,
      '',
      `~${oldFormatted}~`,
      `*${newFormatted}* (\u0627\u0646\u062E\u0641\u0627\u0636 ${pctText})`,
      '',
      `\u0631\u062F \u0639\u0644\u0649 \u0647\u0630\u0647 \u0627\u0644\u0631\u0633\u0627\u0644\u0629 \u0644\u062D\u062C\u0632 \u0645\u0639\u0627\u064A\u0646\u0629.`,
      '',
      footer('ar'),
    ].join('\n');
  }

  // English
  const oldFormatted = formatPrice(data.oldPrice, data.currency, 'en');
  const newFormatted = formatPrice(data.newPrice, data.currency, 'en');

  return [
    `\uD83D\uDCB0 *Price Drop Alert*`,
    '',
    `Hi ${data.clientName},`,
    '',
    'A property you showed interest in has dropped in price:',
    '',
    `\uD83C\uDFE0 ${data.propertyTitle}`,
    `\uD83D\uDCCD ${data.propertyAddress}`,
    '',
    `~${oldFormatted}~`,
    `*${newFormatted}* (${pctText} off)`,
    '',
    'Reply to schedule a viewing.',
    '',
    footer('en'),
  ].join('\n');
}

// ═══════════════════════════════════════════════════════════════════════
// 6. Status Change Alert
// ═══════════════════════════════════════════════════════════════════════

/** Human-readable status labels for WhatsApp messages. */
const STATUS_LABELS_EN: Record<string, string> = {
  SOLD: 'Sold',
  RENTED: 'Rented',
  UNDER_OFFER: 'Under Offer',
  OFF_MARKET: 'Off Market',
  AVAILABLE: 'Available',
  EXPIRED: 'Expired',
};

const STATUS_LABELS_AR: Record<string, string> = {
  SOLD: '\u0645\u064F\u0628\u0627\u0639',
  RENTED: '\u0645\u0624\u062C\u0631',
  UNDER_OFFER: '\u062A\u062D\u062A \u0627\u0644\u0639\u0631\u0636',
  OFF_MARKET: '\u062E\u0627\u0631\u062C \u0627\u0644\u0633\u0648\u0642',
  AVAILABLE: '\u0645\u062A\u0627\u062D',
  EXPIRED: '\u0645\u0646\u062A\u0647\u064A',
};

export function formatStatusChangeAlert(
  data: {
    clientName: string;
    propertyTitle: string;
    newStatus: string;
  },
  language: 'en' | 'ar',
): string {
  if (language === 'ar') {
    const statusLabel = STATUS_LABELS_AR[data.newStatus] ?? data.newStatus;

    return [
      `\uD83D\uDD14 *\u062A\u062D\u062F\u064A\u062B \u062D\u0627\u0644\u0629 \u0627\u0644\u0639\u0642\u0627\u0631*`,
      '',
      `\u0645\u0631\u062D\u0628\u0627\u064B ${data.clientName}${AR_COMMA}`,
      '',
      `\u062A\u063A\u064A\u0631\u062A \u062D\u0627\u0644\u0629 \u0639\u0642\u0627\u0631 \u0643\u0646\u062A \u0645\u0647\u062A\u0645\u0627\u064B \u0628\u0647:`,
      '',
      `\uD83C\uDFE0 ${data.propertyTitle}`,
      `\uD83D\uDCCB \u0627\u0644\u062D\u0627\u0644\u0629 \u0627\u0644\u062C\u062F\u064A\u062F\u0629: *${statusLabel}*`,
      '',
      `\u0631\u062F \u0639\u0644\u0649 \u0647\u0630\u0647 \u0627\u0644\u0631\u0633\u0627\u0644\u0629 \u0644\u0644\u0645\u0632\u064A\u062F \u0645\u0646 \u0627\u0644\u0645\u0639\u0644\u0648\u0645\u0627\u062A.`,
      '',
      footer('ar'),
    ].join('\n');
  }

  // English
  const statusLabel = STATUS_LABELS_EN[data.newStatus] ?? data.newStatus;

  return [
    `\uD83D\uDD14 *Property Status Update*`,
    '',
    `Hi ${data.clientName},`,
    '',
    'A property you showed interest in has a status update:',
    '',
    `\uD83C\uDFE0 ${data.propertyTitle}`,
    `\uD83D\uDCCB New status: *${statusLabel}*`,
    '',
    'Reply for more information.',
    '',
    footer('en'),
  ].join('\n');
}

// ═══════════════════════════════════════════════════════════════════════
// 7. New Matches Notification
// ═══════════════════════════════════════════════════════════════════════

export function formatNewMatchesNotification(
  data: {
    clientName: string;
    matches: Array<{
      title: string;
      address: string;
      bedrooms: number;
      area: number;
      price: number;
      currency: string;
      referenceNumber?: string;
    }>;
  },
  language: 'en' | 'ar',
): string {
  // Cap at 5 matches to keep the message concise
  const displayMatches = data.matches.slice(0, 5);
  const remainingCount = data.matches.length - displayMatches.length;

  if (language === 'ar') {
    const lines: string[] = [
      `\u2728 *\u0639\u0642\u0627\u0631\u0627\u062A \u062C\u062F\u064A\u062F\u0629 \u0645\u0637\u0627\u0628\u0642\u0629*`,
      '',
      `\u0645\u0631\u062D\u0628\u0627\u064B ${data.clientName}${AR_COMMA}`,
      '',
      `\u0648\u062C\u062F\u0646\u0627 *${data.matches.length}* \u0639\u0642\u0627\u0631\u0627\u062A \u062A\u062A\u0637\u0627\u0628\u0642 \u0645\u0639 \u0645\u062A\u0637\u0644\u0628\u0627\u062A\u0643:`,
      '',
    ];

    for (let i = 0; i < displayMatches.length; i++) {
      const m = displayMatches[i];
      const priceStr = formatPrice(m.price, m.currency, 'ar');
      const refStr = m.referenceNumber ? ` (${m.referenceNumber})` : '';

      lines.push(`*${i + 1}.* ${m.title}${refStr}`);
      lines.push(`   \uD83D\uDCCD ${m.address}`);
      lines.push(`   \uD83D\uDECF ${m.bedrooms} \u063A\u0631\u0641 \u0646\u0648\u0645 \u2022 \uD83D\uDCD0 ${m.area.toLocaleString('ar-QA')} \u0645\u00B2`);
      lines.push(`   \uD83D\uDCB0 ${priceStr}`);

      if (i < displayMatches.length - 1) {
        lines.push('');
      }
    }

    if (remainingCount > 0) {
      lines.push('');
      lines.push(`\u0648 *${remainingCount}* \u0639\u0642\u0627\u0631\u0627\u062A \u0623\u062E\u0631\u0649...`);
    }

    lines.push('');
    lines.push(`\u0631\u062F \u0628\u0631\u0642\u0645 \u0627\u0644\u0639\u0642\u0627\u0631 \u0644\u062D\u062C\u0632 \u0645\u0639\u0627\u064A\u0646\u0629.`);
    lines.push('');
    lines.push(footer('ar'));

    return lines.join('\n');
  }

  // English
  const lines: string[] = [
    `\u2728 *New Matching Properties*`,
    '',
    `Hi ${data.clientName},`,
    '',
    `We found *${data.matches.length}* properties matching your criteria:`,
    '',
  ];

  for (let i = 0; i < displayMatches.length; i++) {
    const m = displayMatches[i];
    const priceStr = formatPrice(m.price, m.currency, 'en');
    const refStr = m.referenceNumber ? ` (${m.referenceNumber})` : '';

    lines.push(`*${i + 1}.* ${m.title}${refStr}`);
    lines.push(`   \uD83D\uDCCD ${m.address}`);
    lines.push(`   \uD83D\uDECF ${m.bedrooms} BR \u2022 \uD83D\uDCD0 ${m.area.toLocaleString('en-QA')} sqm`);
    lines.push(`   \uD83D\uDCB0 ${priceStr}`);

    if (i < displayMatches.length - 1) {
      lines.push('');
    }
  }

  if (remainingCount > 0) {
    lines.push('');
    lines.push(`And *${remainingCount}* more...`);
  }

  lines.push('');
  lines.push('Reply with a property number to schedule a viewing.');
  lines.push('');
  lines.push(footer('en'));

  return lines.join('\n');
}
