/**
 * GET    /api/page-studio/pages/[pageId] — fetch a page for editing
 * DELETE /api/page-studio/pages/[pageId] — remove a page
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

async function resolveOwnership(pageId: string, userId: string) {
  const page = await prisma.studioPage.findUnique({
    where: { id: pageId },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!page) return { error: "Page not found" as const, status: 404 };
  if (!page.brand.organization.memberships.some((m) => m.userId === userId)) {
    return { error: "Access denied" as const, status: 403 };
  }
  return { page };
}

export async function GET(_req: Request, { params }: { params: { pageId: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const resolved = await resolveOwnership(params.pageId, user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });
  return NextResponse.json({ page: resolved.page });
}

export async function DELETE(_req: Request, { params }: { params: { pageId: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const resolved = await resolveOwnership(params.pageId, user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });
  await prisma.studioPage.delete({ where: { id: params.pageId } });
  return NextResponse.json({ ok: true });
}
