/**
 * POST /api/feedback — stores user-submitted feedback (bug, feature
 * request, question) with optional screenshot. Called by the floating
 * FeedbackWidget that appears on every page.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const user = await getCurrentUser();

  try {
    const form = await req.formData();
    const type = (form.get("type") as string) || "bug";
    const description = (form.get("description") as string) || "";
    const pageUrl = (form.get("url") as string) || "";
    const userAgent = (form.get("userAgent") as string) || "";
    const viewport = (form.get("viewport") as string) || "";
    const screenshotFile = form.get("screenshot") as File | null;

    let screenshotB64: string | null = null;
    if (screenshotFile && screenshotFile.size > 0 && screenshotFile.size < 5_000_000) {
      const buf = Buffer.from(await screenshotFile.arrayBuffer());
      screenshotB64 = buf.toString("base64");
    }

    await prisma.platformEvent.create({
      data: {
        action: "feedback_submitted",
        category: "feedback",
        userId: user?.id ?? null,
        brandId: null,
        metadata: {
          type,
          description: description.slice(0, 5000),
          pageUrl,
          userAgent: userAgent.slice(0, 500),
          viewport,
          userEmail: user?.email ?? "anonymous",
          hasScreenshot: !!screenshotB64,
          screenshot: screenshotB64?.slice(0, 200_000) ?? null,
        },
      },
    });

    console.info("[feedback]", {
      type,
      user: user?.email ?? "anon",
      page: pageUrl,
      descLen: description.length,
      hasScreenshot: !!screenshotB64,
    });

    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error("[feedback] Error:", err instanceof Error ? err.message : String(err));
    return NextResponse.json({ error: "Failed to submit feedback" }, { status: 500 });
  }
}
