import { NextRequest, NextResponse } from "next/server";
 
// Địa chỉ API chat thật (gọi từ server để tránh lỗi CORS khi gọi trực tiếp từ trình duyệt)
const SARVIS_API_URL = "http://sagent.io.vn/sarvis/177";
 
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const userMessage: string | undefined = body?.message;
    const attachment = body?.attachment ?? null; // { dataUrl, mimeType, name } | null
 
    if ((!userMessage || !userMessage.trim()) && !attachment) {
      return NextResponse.json(
        { error: "Thiếu nội dung tin nhắn" },
        { status: 400 }
      );
    }
 
    const upstream = await fetch(SARVIS_API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      // NOTE: chưa có tài liệu chính thức cho field body của Sarvis API.
      // "message" là giả định phổ biến nhất — nếu API yêu cầu field khác (vd: "text", "content", "query"),
      // chỉnh lại object bên dưới cho khớp.
      //
      // "attachment" là GIẢ ĐỊNH THÊM cho tính năng gửi ảnh/media — nhiều API chat
      // KHÔNG hỗ trợ nhận file dạng base64 qua JSON như thế này, mà cần:
      //   (a) một endpoint upload riêng trả về URL, rồi gửi URL đó kèm message, hoặc
      //   (b) multipart/form-data thay vì JSON.
      // Nếu Sarvis API không nhận field này, ảnh/media sẽ vẫn hiển thị đúng trong
      // khung chat (do lưu ở phía client) nhưng KHÔNG được gửi tới hệ thống AI thật.
      body: JSON.stringify({
        message: userMessage ?? "",
        attachment,
      }),
    });
 
    if (!upstream.ok) {
      const detail = await upstream.text().catch(() => "");
      return NextResponse.json(
        { error: `Sarvis API phản hồi lỗi (${upstream.status})`, detail },
        { status: 502 }
      );
    }
 
    const contentType = upstream.headers.get("content-type") || "";
    const raw = contentType.includes("application/json")
      ? await upstream.json()
      : await upstream.text();
 
    const reply = extractReply(raw);
 
    return NextResponse.json({ reply, raw });
  } catch (err) {
    console.error("Chat proxy error:", err);
    return NextResponse.json(
      { error: "Không thể kết nối tới máy chủ chat. Vui lòng thử lại." },
      { status: 500 }
    );
  }
}
 
/**
 * Sarvis API hiện chưa có tài liệu công khai mô tả rõ field trả về.
 * Hàm này thử dò qua các tên field phổ biến nhất để lấy nội dung phản hồi.
 * Nếu anh biết chính xác field API trả về (vd: chỉ luôn là `data.answer`),
 * có thể rút gọn hàm này lại cho đơn giản và chắc chắn hơn.
 */
function extractReply(raw: unknown): string {
  if (typeof raw === "string") return raw;
 
  if (raw && typeof raw === "object") {
    const obj = raw as Record<string, any>;
    const candidateKeys = [
      "reply",
      "message",
      "response",
      "answer",
      "text",
      "content",
    ];
 
    for (const key of candidateKeys) {
      if (typeof obj[key] === "string" && obj[key].trim()) return obj[key];
    }
 
    // Một số API bọc kết quả trong field "data"
    if (obj.data && typeof obj.data === "object") {
      for (const key of candidateKeys) {
        if (typeof obj.data[key] === "string" && obj.data[key].trim()) {
          return obj.data[key];
        }
      }
    }
    if (typeof obj.data === "string" && obj.data.trim()) return obj.data;
  }
 
  return "Xin lỗi, hệ thống không trả về nội dung hợp lệ.";
}