import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { exportBrief } from "@/lib/services/content-export";

/**
 * GET /api/content-briefs/export?id=xxx&format=outline
 *
 * Formats: outline | plaintext | gdocs | word
 *
 * Returns export-ready content in the requested format.
 */
export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const briefId = searchParams.get("id");
  const format = searchParams.get("format") as "outline" | "plaintext" | "gdocs" | "word" | null;

  if (!briefId) return NextResponse.json({ error: "id is required" }, { status: 400 });
  if (!format || !["outline", "plaintext", "gdocs", "word"].includes(format)) {
    return NextResponse.json({ error: "format must be outline, plaintext, gdocs, or word" }, { status: 400 });
  }

  const brief = await prisma.contentBrief.findUnique({
    where: { id: briefId },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!brief) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!brief.brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const output = exportBrief(
    {
      id: brief.id,
      type: brief.type,
      title: brief.title,
      primaryKeyword: brief.primaryKeyword,
      primaryTopic: brief.primaryTopic,
      brandName: brief.brandName,
      city: brief.city,
      service: brief.service,
      contentScore: brief.contentScore,
      subScores: brief.subScores,
      sections: brief.sections,
      internalLinks: brief.internalLinks,
      writerNotes: brief.writerNotes,
      tone: brief.tone,
      humanizationMode: brief.humanizationMode,
    },
    format
  );

  return NextResponse.json(output);
}
