/**
 * Layout Manager — CRUD for saved layouts.
 */

import { prisma } from "@/lib/prisma";
import type { WidgetConfig } from "./widget-registry";

export async function saveLayout(
  brandId: string, page: string, name: string, widgets: WidgetConfig[],
  isDefault = false, createdBy?: string,
) {
  if (isDefault) {
    await prisma.savedLayout.updateMany({ where: { brandId, page, isDefault: true }, data: { isDefault: false } });
  }
  // Upsert by brandId + page + name
  const existing = await prisma.savedLayout.findFirst({ where: { brandId, page, name } });
  if (existing) {
    return prisma.savedLayout.update({ where: { id: existing.id }, data: { widgets: widgets as unknown as object, isDefault } });
  }
  return prisma.savedLayout.create({ data: { brandId, page, name, widgets: widgets as unknown as object, isDefault, createdBy } });
}

export async function getLayouts(brandId: string, page: string) {
  return prisma.savedLayout.findMany({ where: { brandId, page }, orderBy: { createdAt: "asc" } });
}

export async function getDefaultLayout(brandId: string, page: string) {
  return prisma.savedLayout.findFirst({ where: { brandId, page, isDefault: true } });
}

export async function deleteLayout(id: string) {
  await prisma.savedLayout.delete({ where: { id } });
}

export async function setDefault(id: string, brandId: string, page: string) {
  await prisma.savedLayout.updateMany({ where: { brandId, page, isDefault: true }, data: { isDefault: false } });
  await prisma.savedLayout.update({ where: { id }, data: { isDefault: true } });
}
