/**
 * Layout API client — CRUD for user dashboard layouts
 */

import type { UserLayout, WidgetPlacement } from "@mosaic/shared";
import { apiGet, apiPost, apiPatch } from "./client";

export interface CreateLayoutPayload {
  name: string;
  isDefault?: boolean;
  layout: WidgetPlacement[];
  metadata?: Record<string, unknown>;
}

export interface UpdateLayoutPayload {
  name?: string;
  isDefault?: boolean;
  layout?: WidgetPlacement[];
  metadata?: Record<string, unknown>;
}

/**
 * Fetch the user's default layout for the active workspace.
 * Returns null if no layout exists (404).
 */
export async function fetchDefaultLayout(workspaceId: string): Promise<UserLayout | null> {
  try {
    return await apiGet<UserLayout>("/api/layouts/default", workspaceId);
  } catch {
    // 404 = no layout yet — not an error
    return null;
  }
}

/**
 * Create a new layout.
 */
export async function createLayout(
  workspaceId: string,
  payload: CreateLayoutPayload
): Promise<UserLayout> {
  return apiPost<UserLayout>("/api/layouts", payload, workspaceId);
}

/**
 * Update an existing layout (partial patch).
 */
export async function updateLayout(
  workspaceId: string,
  layoutId: string,
  payload: UpdateLayoutPayload
): Promise<UserLayout> {
  return apiPatch<UserLayout>(`/api/layouts/${layoutId}`, payload, workspaceId);
}
