/**
 * GET /api/writing-assistant/documents/[id] — Get a single document.
 * DELETE /api/writing-assistant/documents/[id] — Delete a document.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

async function verifyDocAccess(id: string, userId: string) {
  const doc = await prisma.writingDocument.findUnique({
    where: { id },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!doc) return { error: "Not found" as const, status: 404 };
  if (!doc.brand.organization.memberships.some((m) => m.userId === userId)) {
    return { error: "Access denied" as const, status: 403 };
  }
  return { doc };
}

export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const { id } = await params;
  const access = await verifyDocAccess(id, user.id);
  if ("error" in access) return NextResponse.json({ error: access.error }, { status: access.status });
  return NextResponse.json({ document: access.doc });
}

export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const { id } = await params;
  const access = await verifyDocAccess(id, user.id);
  if ("error" in access) return NextResponse.json({ error: access.error }, { status: access.status });
  await prisma.writingDocument.delete({ where: { id } });
  return NextResponse.json({ ok: true });
}
