/**
 * Dev-only KB seeding endpoint.
 *
 * Populates `company_knowledge_base` for the organization that owns the
 * TWILIO_WHATSAPP_NUMBER (currently "al Macron city"). Used by the test
 * harness to verify the WhatsApp AI engine actually reads from the
 * knowledge base when answering questions.
 *
 * GET  — returns the resolved org + a count of existing KB entries
 * POST — seeds the mock clinic KB entries (replace=true wipes existing)
 *
 * NOT for production. Only runs when NODE_ENV !== "production".
 */

import { NextRequest, NextResponse } from "next/server";
import { convexQuery, convexMutation } from "@/lib/convex-client";
import { twilioWhatsAppService } from "@/lib/services/twilio-whatsapp.service";

type KBEntry = {
  question: string;
  answer: string;
  category?: string;
  language: string;
  priority?: number;
};

// Mock company info — deliberately specific details so we can verify the AI
// pulled them from the KB vs made them up.
const ENGLISH_ENTRIES: KBEntry[] = [
  {
    category: "hours",
    priority: 100,
    language: "en",
    question: "What are your opening hours and working days?",
    answer:
      "al Macron city clinic is open Sunday to Thursday from 8:00 AM to 9:00 PM, Friday from 2:00 PM to 9:00 PM (after Jumu'ah prayer), and Saturday from 9:00 AM to 6:00 PM. We are closed on the first day of every Eid.",
  },
  {
    category: "location",
    priority: 90,
    language: "en",
    question: "Where are you located? What is the address?",
    answer:
      "We are located on the 3rd floor of Burj al Mana Tower, Al Sadd Street, Doha, Qatar. The nearest Metro station is Al Sadd (Red Line), a 4 minute walk from the clinic. Our Google Maps pin is titled 'al Macron city Clinic Doha'.",
  },
  {
    category: "parking",
    priority: 80,
    language: "en",
    question: "Is there parking available?",
    answer:
      "Yes — free underground patient parking is available on basement levels B2 and B3 of Burj al Mana Tower. Please collect a validation sticker at reception; without it the parking fee is 10 QAR per hour.",
  },
  {
    category: "insurance",
    priority: 95,
    language: "en",
    question: "Do you accept insurance? Which insurance providers do you take?",
    answer:
      "We are in-network with Qatar Insurance Company (QIC), AXA Gulf, Allianz Care, Bupa Global, Daman, and MetLife. We do NOT currently accept Tawuniya or Al Rajhi Takaful. Please bring your insurance card and Qatar ID on the day of your appointment.",
  },
  {
    category: "pricing",
    priority: 85,
    language: "en",
    question: "How much does a consultation cost? What are your prices?",
    answer:
      "General consultation is 150 QAR, follow-up within 14 days is 80 QAR, and specialist consultation (dermatology, cardiology, pediatrics) is 250 QAR. A 50 QAR refundable deposit is required at booking — it is applied toward your final bill.",
  },
  {
    category: "cancellation",
    priority: 70,
    language: "en",
    question: "What is your cancellation policy? Can I reschedule?",
    answer:
      "You can cancel or reschedule free of charge up to 4 hours before your appointment by replying to this WhatsApp chat. Cancellations within 4 hours forfeit the 50 QAR deposit. No-shows are charged the full consultation fee.",
  },
  {
    category: "doctors",
    priority: 75,
    language: "en",
    question: "Who are your doctors? What specialists do you have?",
    answer:
      "Our medical team: Dr. Fatima Al-Kuwari (General Medicine, Head of Clinic, 15 years experience), Dr. Omar Haddad (Cardiology, trained at King's College London), Dr. Layla Al-Emadi (Dermatology & Aesthetic Medicine), and Dr. Youssef Khalil (Pediatrics). All doctors are MOPH licensed.",
  },
  {
    category: "services",
    priority: 60,
    language: "en",
    question: "What services and treatments do you offer?",
    answer:
      "We offer general consultations, follow-ups, blood tests (results in 24 hours), ECG, vaccinations (including children's routine and travel vaccines), minor procedures, skin treatments, and home visits within a 10km radius of Al Sadd for an extra 100 QAR call-out fee.",
  },
  {
    category: "emergency",
    priority: 50,
    language: "en",
    question: "Do you handle emergencies? Is there a 24/7 line?",
    answer:
      "We are NOT an emergency clinic. For emergencies please call 999 (Hamad General Hospital) or go to the nearest ER. Our on-call nurse line is available for non-urgent questions from 9 PM to 8 AM on +974 4000 1234.",
  },
  {
    category: "languages",
    priority: 40,
    language: "en",
    question: "What languages do your doctors speak?",
    answer:
      "All our doctors speak fluent English and Arabic. Dr. Omar Haddad also speaks French, and Dr. Youssef Khalil speaks Urdu. Our reception team can assist in English, Arabic, Hindi, and Filipino.",
  },
];

const ARABIC_ENTRIES: KBEntry[] = [
  {
    category: "hours",
    priority: 100,
    language: "ar",
    question: "شنو ساعات الدوام؟ متى مفتوحين؟",
    answer:
      "عيادة المكرون سيتي مفتوحة من الأحد إلى الخميس من الساعة 8 الصباح إلى 9 الليل، والجمعة من 2 الظهر إلى 9 الليل (بعد صلاة الجمعة)، والسبت من 9 الصباح إلى 6 المغرب. مغلقون أول يوم من كل عيد.",
  },
  {
    category: "location",
    priority: 90,
    language: "ar",
    question: "وين مكانكم؟ شلون أوصل لكم؟",
    answer:
      "موقعنا في الطابق الثالث من برج المانع، شارع السد، الدوحة، قطر. أقرب محطة مترو هي السد (الخط الأحمر)، على بعد 4 دقايق مشي من العيادة.",
  },
  {
    category: "insurance",
    priority: 95,
    language: "ar",
    question: "تقبلون تأمين؟ شنو شركات التأمين عندكم؟",
    answer:
      "نقبل قطر للتأمين (QIC)، أكسا الخليج، أليانز كير، بوبا العالمية، ضمان، وميتلايف. ما نقبل التعاونية ولا الراجحي تكافل. يا ليت تجيب بطاقة التأمين والبطاقة الشخصية يوم الموعد.",
  },
  {
    category: "pricing",
    priority: 85,
    language: "ar",
    question: "شنو سعر الكشف؟ بكم الاستشارة؟",
    answer:
      "الاستشارة العامة بـ 150 ريال، والمراجعة خلال 14 يوم بـ 80 ريال، والاستشارة التخصصية (جلدية، قلب، أطفال) بـ 250 ريال. يتطلب الحجز دفع 50 ريال عربون — يتم خصمه من الفاتورة النهائية.",
  },
  {
    category: "parking",
    priority: 80,
    language: "ar",
    question: "عندكم موقف سيارات؟",
    answer:
      "إي، موقف سيارات مجاني للمرضى في القبو B2 و B3 من برج المانع. يرجى أخذ ملصق تحقق من الاستقبال، وإلا رسوم الموقف 10 ريال للساعة.",
  },
  {
    category: "doctors",
    priority: 75,
    language: "ar",
    question: "مين الدكاترة عندكم؟ شنو التخصصات؟",
    answer:
      "الفريق الطبي: د. فاطمة الكواري (طب عام، رئيسة العيادة، 15 سنة خبرة)، د. عمر حداد (قلب، تدرّب في كينجز كولدج لندن)، د. ليلى العمادي (جلدية وتجميل)، د. يوسف خليل (أطفال). جميع الدكاترة مرخصين من وزارة الصحة العامة.",
  },
];

const ALL_ENTRIES = [...ENGLISH_ENTRIES, ...ARABIC_ENTRIES];

async function resolveClinicOrg() {
  const twilioNumber = process.env.TWILIO_WHATSAPP_NUMBER;
  if (!twilioNumber) {
    throw new Error("TWILIO_WHATSAPP_NUMBER env var is not set");
  }
  // The router looks up by "whatsapp:+<number>" prefix for incoming messages
  // but stores the raw E.164 number on the org record. Try both.
  const cleaned = twilioNumber.startsWith("whatsapp:")
    ? twilioNumber.substring("whatsapp:".length)
    : twilioNumber;

  let org = await twilioWhatsAppService.getOrgByTwilioNumber(cleaned);
  if (!org) {
    org = await twilioWhatsAppService.getOrgByTwilioNumber(`whatsapp:${cleaned}`);
  }
  return org;
}

export async function GET() {
  if (process.env.ENABLE_DEV_ROUTES !== "1") {
    return NextResponse.json({ error: "Dev routes disabled" }, { status: 403 });
  }

  try {
    const org = await resolveClinicOrg();
    if (!org) {
      return NextResponse.json(
        {
          error: "Could not resolve org from TWILIO_WHATSAPP_NUMBER",
          twilioNumber: process.env.TWILIO_WHATSAPP_NUMBER,
        },
        { status: 404 },
      );
    }

    // Count current entries
    const existing = await convexQuery<unknown[]>(
      "whatsapp/queries:getKnowledgeBaseEntries",
      { organizationId: org.id, limit: 1000 },
    );

    return NextResponse.json({
      org: { id: org.id, name: org.name, ownerId: org.ownerId },
      existingKbEntryCount: Array.isArray(existing) ? existing.length : 0,
      availableSeedEntries: ALL_ENTRIES.length,
    });
  } catch (error) {
    return NextResponse.json(
      { error: String(error instanceof Error ? error.message : error) },
      { status: 500 },
    );
  }
}

export async function POST(req: NextRequest) {
  if (process.env.ENABLE_DEV_ROUTES !== "1") {
    return NextResponse.json({ error: "Dev routes disabled" }, { status: 403 });
  }

  try {
    const body = await req.json().catch(() => ({}));
    const replace = body?.replace === true;

    const org = await resolveClinicOrg();
    if (!org) {
      return NextResponse.json(
        { error: "Could not resolve org from TWILIO_WHATSAPP_NUMBER" },
        { status: 404 },
      );
    }

    const result = await convexMutation<{ inserted: number; replaced: boolean }>(
      "whatsapp/mutations:seedCompanyKnowledgeBase",
      {
        organizationId: org.id,
        replace,
        entries: ALL_ENTRIES,
      },
    );

    return NextResponse.json({
      ok: true,
      org: { id: org.id, name: org.name },
      ...result,
    });
  } catch (error) {
    return NextResponse.json(
      { error: String(error instanceof Error ? error.message : error) },
      { status: 500 },
    );
  }
}
