/**
 * PUT /api/layouts/[id]/default — set this layout as the default.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { setDefault } from "@/lib/layouts/layout-manager";

export const dynamic = "force-dynamic";

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

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

  await setDefault(params.id, layout.brandId, layout.page);
  return NextResponse.json({ ok: true });
}
