import OpenAI from "openai";
import { NextRequest } from "next/server";

export const runtime = "nodejs";

const SYSTEM_PROMPT = `You are KC Assistant, the friendly AI helper for KC Systems Limited — a Malaysian platform offering e-commerce, travel packages, a career jobs portal, knowledge journals, and international scholarships.

Personality: warm, helpful, concise, and professional. Use natural conversational language. Do not use excessive emojis.

Your goals:
1. Greet the user warmly and offer assistance.
2. After the user's FIRST message, naturally ask for their name and email within your reply so you can follow up if needed. Do this smoothly — not as a rigid form request.
3. Once you have both name and email, acknowledge them personally and continue helping.
4. Answer questions about KC Systems products and services.

Key information about KC Systems Limited:
- Website: https://kc-systems.com
- Shop: Browse and purchase products online. No subscription needed — free account is enough.
- Tours & Travel: Discover and book travel packages. No subscription needed — free account is enough.
- Jobs Portal: Search jobs loaded from external APIs, build a resume, and apply for jobs. Requires Job Seeker subscription ($49/month).
- Journals: Read and publish knowledge articles and journals. Requires Journal subscription ($49/month).
- Scholarships: Discover worldwide scholarship opportunities. Free to browse.
- Contact / WhatsApp: +60188721718

Always be honest. If you don't know an answer, offer to connect the user with the team via WhatsApp or email.`;

export async function POST(req: NextRequest) {
  try {
    const apiKey = process.env.OPENAI_API_KEY;
    if (!apiKey) {
      return Response.json(
        { error: "AI service is not configured. Please contact support." },
        { status: 503 }
      );
    }

    const body = await req.json();
    const { messages } = body as {
      messages: { role: "user" | "assistant"; content: string }[];
    };

    if (!Array.isArray(messages) || messages.length === 0) {
      return Response.json({ error: "Invalid request." }, { status: 400 });
    }

    // Limit history to last 20 messages to keep context manageable
    const trimmedMessages = messages.slice(-20);

    const openai = new OpenAI({ apiKey });

    const stream = await openai.chat.completions.create({
      model: process.env.OPENAI_MODEL ?? "gpt-4o-mini",
      messages: [
        { role: "system", content: SYSTEM_PROMPT },
        ...trimmedMessages,
      ],
      max_tokens: 500,
      temperature: 0.7,
      stream: true,
    });

    const encoder = new TextEncoder();

    const readable = new ReadableStream({
      async start(controller) {
        for await (const chunk of stream) {
          const text = chunk.choices[0]?.delta?.content ?? "";
          if (text) {
            controller.enqueue(encoder.encode(text));
          }
        }
        controller.close();
      },
    });

    return new Response(readable, {
      headers: {
        "Content-Type": "text/plain; charset=utf-8",
        "Cache-Control": "no-cache",
        "X-Content-Type-Options": "nosniff",
      },
    });
  } catch (err) {
    console.error("[chat/route]", err);
    return Response.json(
      { error: "Something went wrong. Please try again." },
      { status: 500 }
    );
  }
}
