/**
 * FAQ Suggestion Service
 *
 * Generates FAQ suggestions from unanswered questions and manages
 * the approval workflow. Also handles cross-sector anonymized learning.
 */

import { convexMutation, convexQuery } from "@/lib/convex-client";
import { logger } from "@/lib/logger";

// Minimum frequency before suggesting an FAQ
const MIN_FREQUENCY_FOR_SUGGESTION = 3;

/**
 * Anonymize a question for cross-sector learning.
 * Strips PII: phone numbers, emails, names, specific dates.
 */
function anonymizeQuestion(question: string): string {
  return question
    .replace(/\+?\d[\d\s-]{8,}/g, "[PHONE]")
    .replace(/[\w.-]+@[\w.-]+\.\w+/g, "[EMAIL]")
    .replace(/\d{1,2}[/\-]\d{1,2}[/\-]\d{2,4}/g, "[DATE]")
    .replace(/\d{4}-\d{2}-\d{2}/g, "[DATE]")
    .toLowerCase()
    .trim();
}

interface UnansweredQuestionRow {
  _id: string;
  question: string;
  frequency: number;
  language: string;
}

/**
 * Process unanswered questions for an org and generate FAQ suggestions.
 * Called periodically or when unanswered question count exceeds threshold.
 */
export async function generateFAQSuggestions(
  organizationId: string,
): Promise<number> {
  try {
    // Get open unanswered questions with enough frequency
    const questions = (await convexQuery(
      "whatsapp/queries:getUnansweredQuestions",
      { organizationId, status: "open", limit: 100 },
    )) as UnansweredQuestionRow[] | null;

    if (!Array.isArray(questions)) return 0;

    // Filter by minimum frequency
    const frequent = questions.filter(
      (q) => q.frequency >= MIN_FREQUENCY_FOR_SUGGESTION,
    );
    let suggested = 0;

    for (const q of frequent) {
      // Create a suggested FAQ with a template answer
      // (Business owner will customize the answer)
      const templateAnswer =
        q.language === "ar"
          ? "يرجى التواصل معنا للحصول على المزيد من المعلومات حول هذا الاستفسار."
          : "Please contact us for more information about this inquiry.";

      await convexMutation("whatsapp/mutations:createSuggestedFaq", {
        organizationId,
        question: q.question,
        suggestedAnswer: templateAnswer,
        language: q.language,
        frequency: q.frequency,
        sourceQuestionIds: [q._id],
      });

      suggested++;
    }

    logger.info("[FAQ Suggestions] Generated", {
      organizationId,
      suggested,
      total: questions.length,
    });
    return suggested;
  } catch (error) {
    logger.error("[FAQ Suggestions] Failed", { organizationId, error });
    return 0;
  }
}

/**
 * Approve a suggested FAQ — marks it as approved. The caller is responsible
 * for copying the approved content into company_knowledge_base.
 */
export async function approveSuggestedFaq(
  faqId: string,
  approvedBy: string,
  _customAnswer?: string,
): Promise<boolean> {
  try {
    await convexMutation("whatsapp/mutations:updateSuggestedFaqStatus", {
      id: faqId,
      status: "approved",
      approvedBy,
    });

    logger.info("[FAQ Suggestions] Approved", { faqId, approvedBy });
    return true;
  } catch (error) {
    logger.error("[FAQ Suggestions] Approval failed", { faqId, error });
    return false;
  }
}

/**
 * Reject a suggested FAQ.
 */
export async function rejectSuggestedFaq(faqId: string): Promise<boolean> {
  try {
    await convexMutation("whatsapp/mutations:updateSuggestedFaqStatus", {
      id: faqId,
      status: "rejected",
    });
    return true;
  } catch (error) {
    logger.error("[FAQ Suggestions] Rejection failed", { faqId, error });
    return false;
  }
}

/**
 * Track a question pattern for cross-sector learning (anonymized).
 * Called after tracking an unanswered question.
 * Non-blocking — failures should never affect the conversation flow.
 */
export async function trackCrossSectorQuestion(
  sector: string,
  question: string,
  language: string,
): Promise<void> {
  try {
    const pattern = anonymizeQuestion(question);
    if (pattern.length < 5) return;

    await convexMutation("whatsapp/mutations:trackSectorCommonQuestion", {
      sector,
      questionPattern: pattern,
      language,
    });
  } catch (error) {
    logger.error("[Cross-Sector] Tracking failed", { sector, error });
  }
}
