/**
 * PUT /api/schema/[id] — Update a schema.
 * DELETE /api/schema/[id] — Delete a schema.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

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

export async function PUT(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 verifySchemaAccess(id, user.id);
  if ("error" in access) return NextResponse.json({ error: access.error }, { status: access.status });

  const body = await req.json().catch(() => null);
  if (!body) return NextResponse.json({ error: "Body required" }, { status: 400 });

  const schema = await prisma.schemaMarkup.update({
    where: { id },
    data: {
      ...(body.jsonLd !== undefined && { jsonLd: body.jsonLd }),
      ...(body.status !== undefined && { status: body.status }),
      ...(body.autoInject !== undefined && { autoInject: body.autoInject }),
      ...(body.schemaType !== undefined && { schemaType: body.schemaType }),
      ...(body.pageUrl !== undefined && { pageUrl: body.pageUrl }),
    },
  });

  return NextResponse.json({ schema });
}

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 verifySchemaAccess(id, user.id);
  if ("error" in access) return NextResponse.json({ error: access.error }, { status: access.status });

  await prisma.schemaMarkup.delete({ where: { id } });
  return NextResponse.json({ ok: true });
}
