import { sendCommand } from "./client";
import { pickCase } from "./normalize";

export type ListDocumentDto = {
  id: string;
  label: string;
  content: string;
  createdAt: string;
  updatedAt: string;
};

export type CreateListPayload = {
  label: string;
  content?: string;
};

export type UpdateListPayload = {
  label?: string;
  content?: string;
};

type ListDocumentDtoRaw = {
  id?: string;
  label?: string;
  content?: string;
  createdAt?: string;
  updatedAt?: string;
  Id?: string;
  Label?: string;
  Content?: string;
  CreatedAt?: string;
  UpdatedAt?: string;
};

export function normalizeList(raw: ListDocumentDtoRaw): ListDocumentDto {
  return {
    id: pickCase(raw, "id", "Id", ""),
    label: pickCase(raw, "label", "Label", ""),
    content: pickCase(raw, "content", "Content", ""),
    createdAt: pickCase(raw, "createdAt", "CreatedAt", ""),
    updatedAt: pickCase(raw, "updatedAt", "UpdatedAt", ""),
  };
}

export async function listLists(): Promise<ListDocumentDto[]> {
  const data = await sendCommand<ListDocumentDtoRaw[]>({
    action: "lists.list",
  });
  return data.map(normalizeList).filter((item) => Boolean(item.id));
}

export async function getList(id: string): Promise<ListDocumentDto | null> {
  const data = await sendCommand<ListDocumentDtoRaw | null>({
    action: "lists.get",
    id,
  });
  if (!data) return null;
  const normalized = normalizeList(data);
  return normalized.id ? normalized : null;
}

export async function createList(
  payload: CreateListPayload,
): Promise<ListDocumentDto> {
  const data = await sendCommand<ListDocumentDtoRaw>({
    action: "lists.create",
    payload,
  });
  return normalizeList(data);
}

export function updateList(
  id: string,
  payload: UpdateListPayload,
): Promise<boolean> {
  return sendCommand<boolean>({
    action: "lists.update",
    id,
    payload,
  });
}

export function deleteList(id: string): Promise<boolean> {
  return sendCommand<boolean>({
    action: "lists.delete",
    id,
  });
}
