/**
 * WhatsApp Greeting Service
 *
 * Builds the first-message greeting for a new WhatsApp conversation.
 * Uses the org's custom greeting if configured, otherwise falls back
 * to the default bilingual language-selection prompt.
 *
 * Used by all 3 WhatsApp webhooks:
 *   - app/api/integrations/whatsapp/webhook/route.ts (Meta Cloud API)
 *   - app/api/webhooks/twilio-whatsapp/route.ts (Twilio generic)
 *   - app/api/webhooks/twilio-whatsapp-re/route.ts (Twilio real estate)
 */

import prisma from "@/lib/db";
import { logger } from "@/lib/logger";

export interface GreetingResult {
  text: string;
  requiresLanguageSelection: boolean;
}

interface OrgGreetingFields {
  name: string;
  greetingMessageEn?: string | null;
  greetingMessageAr?: string | null;
  autoGreetingEnabled?: boolean | null;
}

/**
 * Build the greeting message for a new conversation.
 * - If the org has `autoGreetingEnabled === false`, return an empty text (no greeting sent).
 * - If sectorKey is 'health_care', return a simple welcome without language selection.
 * - If the org has set custom greetings (EN and/or AR), use them (with language selection prompt appended).
 * - Otherwise, use the default bilingual greeting.
 */
export async function buildGreetingForOrg(
  organizationId: string,
  orgName: string,
  sectorKey?: string,
): Promise<GreetingResult> {
  let org: OrgGreetingFields | null = null;
  try {
    const row = await prisma.organizations.findFirst({
      where: { id: organizationId },
      select: {
        name: true,
        greetingMessageEn: true,
        greetingMessageAr: true,
        autoGreetingEnabled: true,
      },
    });
    if (row) org = row as unknown as OrgGreetingFields;
  } catch (error) {
    logger.warn("Failed to load custom greeting, using default", {
      organizationId,
      error,
    });
  }

  // Explicit opt-out: no greeting sent
  if (org?.autoGreetingEnabled === false) {
    return { text: "", requiresLanguageSelection: false };
  }

  // Health care sector: simple welcome, no language selection menu
  if (sectorKey === "health_care") {
    const displayName = org?.name || orgName;
    return {
      text: `Welcome to ${displayName}! 👋 How can we help you today?`,
      requiresLanguageSelection: false,
    };
  }

  const hasCustomEn = !!(
    org?.greetingMessageEn && org.greetingMessageEn.trim().length > 0
  );
  const hasCustomAr = !!(
    org?.greetingMessageAr && org.greetingMessageAr.trim().length > 0
  );

  if (hasCustomEn || hasCustomAr) {
    // Custom greeting set — append language selection prompt automatically
    const arPart = hasCustomAr ? org!.greetingMessageAr!.trim() : "";
    const enPart = hasCustomEn ? org!.greetingMessageEn!.trim() : "";

    const sections: string[] = [];
    if (arPart) sections.push(arPart);
    if (enPart) sections.push(enPart);
    sections.push(
      "اختر لغتك المفضلة / Please select your preferred language:",
    );
    sections.push("1️⃣ العربية (Arabic)");
    sections.push("2️⃣ English");

    return {
      text: sections.join("\n\n"),
      requiresLanguageSelection: true,
    };
  }

  // Default bilingual greeting (preserves existing behavior exactly)
  return {
    text:
      `هلا! 👋 مشكور على تواصلك مع ${orgName}.\n\n` +
      `Hello! 👋 Thank you for contacting ${orgName}.\n\n` +
      `اختر لغتك المفضلة / Please select your preferred language:\n` +
      `1️⃣ العربية (Arabic)\n` +
      `2️⃣ English`,
    requiresLanguageSelection: true,
  };
}
