import type { SavedCanvas, CanvasItem } from './types';
import type { LayoutItem } from 'react-grid-layout';
import { customRequest } from 'helpers/http';

// 服务端返回的 Canvas 形状（createdAt 是 ISO 字符串）
interface CanvasRecord {
  id: string;
  name: string;
  userId: string;
  items: CanvasItem[];
  layout: LayoutItem[];
  publishedPageCode: string | null;
  publishedAt: string | null;
  createdAt: string;
  updatedAt: string;
}

function toSavedCanvas(r: CanvasRecord): SavedCanvas {
  return {
    id: r.id,
    name: r.name,
    items: r.items ?? [],
    layout: r.layout ?? [],
    publishedPageCode: r.publishedPageCode ?? null,
    publishedAt: r.publishedAt ? new Date(r.publishedAt).getTime() : null,
    createdAt: new Date(r.createdAt).getTime(),
    updatedAt: new Date(r.updatedAt).getTime(),
  };
}

export async function fetchCanvases(): Promise<SavedCanvas[]> {
  const records = await customRequest<CanvasRecord[]>('canvas', 'GET');
  return records.map(toSavedCanvas);
}

export async function fetchCanvas(id: string): Promise<SavedCanvas | null> {
  const record = await customRequest<CanvasRecord | null>(
    `canvas/${id}`,
    'GET',
  );
  if (!record) return null;
  return toSavedCanvas(record);
}

export async function createCanvas(name: string): Promise<SavedCanvas> {
  const record = await customRequest<CanvasRecord>('canvas', 'POST', {
    name,
    items: [],
    layout: [],
  });
  return toSavedCanvas(record);
}

export async function updateCanvas(
  id: string,
  patch: Partial<
    Pick<
      SavedCanvas,
      'name' | 'items' | 'layout' | 'publishedPageCode' | 'publishedAt'
    >
  >,
): Promise<void> {
  await customRequest(`canvas/${id}`, 'PUT', patch);
}

export async function deleteCanvas(id: string): Promise<void> {
  await customRequest(`canvas/${id}`, 'DELETE');
}

export async function publishCanvas(
  id: string,
  dto: { slug: string; pageName: string; parentPageCode?: string },
): Promise<{ success: boolean; pageCode: string }> {
  return customRequest<{ success: boolean; pageCode: string }>(
    `canvas/${id}/publish`,
    'POST',
    dto,
  );
}

export async function unpublishCanvas(id: string): Promise<void> {
  await customRequest(`canvas/${id}/unpublish`, 'DELETE');
}
