import { NextRequest, NextResponse } from "next/server";

const API_URL = process.env.MEEZI_API_URL ?? "http://localhost:5001";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  const { slug } = await params;

  try {
    const res = await fetch(
      `${API_URL}/api/public/website/posts/${encodeURIComponent(slug)}/comments`,
      { next: { revalidate: 60 } }
    );

    if (!res.ok) {
      return NextResponse.json({ comments: [] });
    }

    const json = await res.json();
    // Unwrap ApiResponse<T>: { success, data } → normalize to { comments: [...] }
    const payload = json?.data ?? json;
    const comments = Array.isArray(payload) ? payload : [];
    return NextResponse.json({ comments });
  } catch {
    // API not available — return empty list gracefully
    return NextResponse.json({ comments: [] });
  }
}

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  const { slug } = await params;

  let body: unknown;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const { authorName, authorEmail, content } = body as {
    authorName?: string;
    authorEmail?: string;
    content?: string;
  };

  if (!authorName || !content) {
    return NextResponse.json(
      { error: "authorName and content are required" },
      { status: 400 }
    );
  }

  try {
    const res = await fetch(
      `${API_URL}/api/public/website/posts/${encodeURIComponent(slug)}/comments`,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ authorName, authorEmail, content }),
      }
    );

    if (!res.ok) {
      const text = await res.text();
      return NextResponse.json(
        { error: text || "Upstream error" },
        { status: res.status }
      );
    }

    const data = await res.json();
    return NextResponse.json(data, { status: 201 });
  } catch {
    return NextResponse.json(
      { error: "Failed to reach API" },
      { status: 502 }
    );
  }
}
