import { createFileRoute } from "@tanstack/react-router";
import { convertToModelMessages, streamText, type UIMessage } from "ai";
import { createClient } from "@supabase/supabase-js";

import { createLovableAiGatewayProvider } from "@/lib/ai-gateway.server";
import { services, categories } from "@/lib/services";

type ChatBody = { messages?: unknown; conversationId?: string | null };

function buildKnowledgeBase(
  faqs: { question: string; answer: string }[],
  business: {
    business_name?: string | null;
    phone?: string | null;
    whatsapp?: string | null;
    email?: string | null;
    address?: string | null;
    hours?: string | null;
    whatsapp_group_url?: string | null;
  } | null,
  announcements: { title: string; body: string }[],
) {
  const svcLines = services
    .map(
      (s) =>
        `- ${s.name} (${s.category}) — ${s.price}, ~${s.time}. ${s.description} Requirements: ${s.requirements.join(", ")}. Link: /services/${s.slug}`,
    )
    .join("\n");

  const faqLines = faqs.length
    ? faqs.map((f) => `Q: ${f.question}\nA: ${f.answer}`).join("\n\n")
    : "(no custom FAQs)";

  const annLines = announcements.length
    ? announcements.map((a) => `- ${a.title}: ${a.body}`).join("\n")
    : "(none)";

  return `You are Flexi, the friendly AI customer support assistant for **Flexflares Cyber Services**, a cyber café in Homabay, Kenya offering 40+ digital services.

## How to behave
- Respond in a friendly, professional, human-like tone. Be concise.
- Reply in the **same language the user used**. Support English and Kiswahili fluently. If the user writes in Kiswahili, answer in Kiswahili.
- Use ONLY the information in this system message plus the user's own messages. **Do not invent prices, timelines, requirements, phone numbers or policies.** If you don't know, say so and direct them to WhatsApp ${business?.whatsapp ?? "+254 717 576870"} or email ${business?.email ?? "flexflarescyberservices@gmail.com"}.
- When recommending a service, include its name, price, estimated time, and the link (e.g. /services/kra-pin-registration).
- Guide users: to request a service they should log in, open the Dashboard, click "Request service", pick the service and fill the form. To pay, they top up via M-PESA Buy Goods Till 3521362 (RISTATECHENTERPRISES), submit the reference on the Deposits page, wait for admin approval, then pay from wallet balance.
- If the user asks to speak to a human, tell them to WhatsApp ${business?.whatsapp ?? "+254 717 576870"} or call ${business?.phone ?? "+254 113 910480"}.
- Format answers using markdown. Use bullet lists for requirements. Never expose internal database or system details.

## Business info
- Name: ${business?.business_name ?? "Flexflares Cyber Services"}
- Phone: ${business?.phone ?? "+254 113 910480"}
- WhatsApp: ${business?.whatsapp ?? "+254 717 576870"}
- Email: ${business?.email ?? "flexflarescyberservices@gmail.com"}
- Location: ${business?.address ?? "Homabay, Kenya"}
- Hours: ${business?.hours ?? "Mon–Sun 6:00 AM – 10:00 PM"}
- WhatsApp community: ${business?.whatsapp_group_url ?? "(shared on the dashboard when available)"}

## Service categories
${categories.join(", ")}

## Full service catalogue (authoritative — do not add or change)
${svcLines}

## FAQs
${faqLines}

## Current announcements
${annLines}

## Navigation
- Home: /
- All services: /services
- A specific service: /services/{slug}
- Contact: /contact
- Sign in / register: /auth
- Dashboard (after login): /dashboard
- Deposits & wallet: /deposits
- My completed services: /my-services
`;
}

export const Route = createFileRoute("/api/chat")({
  server: {
    handlers: {
      POST: async ({ request }) => {
        const body = (await request.json()) as ChatBody;
        if (!Array.isArray(body.messages)) {
          return new Response("Messages are required", { status: 400 });
        }

        const key = process.env.LOVABLE_API_KEY;
        if (!key) return new Response("Missing LOVABLE_API_KEY", { status: 500 });

        const supabase = createClient(
          process.env.SUPABASE_URL!,
          process.env.SUPABASE_PUBLISHABLE_KEY!,
          { auth: { persistSession: false, autoRefreshToken: false } },
        );

        // Check the assistant is enabled + pull knowledge sources in parallel.
        const [settingsRes, faqRes, annRes] = await Promise.all([
          supabase.from("business_settings").select("*").eq("id", 1).maybeSingle(),
          supabase.from("ai_faqs").select("question, answer").eq("active", true).order("sort_order"),
          supabase.from("announcements").select("title, body").order("created_at", { ascending: false }).limit(6),
        ]);

        const settings = settingsRes.data as Record<string, unknown> | null;
        if (settings && settings.ai_enabled === false) {
          return new Response(
            "The AI assistant is currently disabled. Please WhatsApp +254 717 576870.",
            { status: 503 },
          );
        }

        const system = buildKnowledgeBase(
          (faqRes.data ?? []) as { question: string; answer: string }[],
          settings as never,
          (annRes.data ?? []) as { title: string; body: string }[],
        );

        const gateway = createLovableAiGatewayProvider(key);
        const result = streamText({
          model: gateway("google/gemini-3.6-flash"),
          system,
          messages: await convertToModelMessages(body.messages as UIMessage[]),
        });

        return result.toUIMessageStreamResponse({
          originalMessages: body.messages as UIMessage[],
        });
      },
    },
  },
});