/**
 * POST /api/layouts/save — save/upsert a layout
 * GET  /api/layouts?brandId=X&page=dashboard — list layouts
 */

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

export const dynamic = "force-dynamic";

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

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

  const body = await req.json().catch(() => null) as Record<string, unknown> | null;
  if (!body?.brandId || !body?.page || !body?.name || !Array.isArray(body.widgets)) {
    return NextResponse.json({ error: "brandId, page, name, widgets[] required" }, { status: 400 });
  }

  const resolved = await authBrand(String(body.brandId), user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });

  const layout = await saveLayout(String(body.brandId), String(body.page), String(body.name), body.widgets as [], !!body.isDefault, user.id);
  return NextResponse.json({ layout });
}

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 brandId = searchParams.get("brandId");
  const page = searchParams.get("page");
  if (!brandId || !page) return NextResponse.json({ error: "brandId and page required" }, { status: 400 });

  const resolved = await authBrand(brandId, user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });

  const layouts = await getLayouts(brandId, page);
  return NextResponse.json({ layouts });
}
