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

export type EntryTemplateItemDto = {
  fileName: string;
  filePath: string;
};

export type EntryTemplateLoadResultDto = {
  fileName: string;
  filePath: string;
  content: string;
};

export type EntryTemplateSaveResultDto = {
  filePath: string;
};

type EntryTemplateItemDtoRaw = {
  fileName?: string;
  filePath?: string;
  FileName?: string;
  FilePath?: string;
};

type EntryTemplateLoadResultDtoRaw = {
  fileName?: string;
  filePath?: string;
  content?: string;
  FileName?: string;
  FilePath?: string;
  Content?: string;
};

type EntryTemplateSaveResultDtoRaw = {
  filePath?: string;
  FilePath?: string;
};

function normalizeTemplateItem(
  raw: EntryTemplateItemDtoRaw,
): EntryTemplateItemDto {
  return {
    fileName: pickCase(raw, "fileName", "FileName", ""),
    filePath: pickCase(raw, "filePath", "FilePath", ""),
  };
}

export async function listEntryTemplates(): Promise<EntryTemplateItemDto[]> {
  const data = await sendCommand<EntryTemplateItemDtoRaw[]>({
    action: "templates.list",
    payload: {},
  });

  return data
    .map(normalizeTemplateItem)
    .filter((item) => Boolean(item.filePath));
}

export async function loadEntryTemplate(
  filePath: string,
): Promise<EntryTemplateLoadResultDto> {
  const data = await sendCommand<EntryTemplateLoadResultDtoRaw>({
    action: "templates.load",
    payload: { filePath },
  });

  return {
    fileName: pickCase(data, "fileName", "FileName", ""),
    filePath: pickCase(data, "filePath", "FilePath", ""),
    content: pickCase(data, "content", "Content", ""),
  };
}

export async function saveEntryTemplate(payload: {
  name: string;
  content: string;
  filePath?: string;
}): Promise<EntryTemplateSaveResultDto> {
  const data = await sendCommand<EntryTemplateSaveResultDtoRaw>({
    action: "templates.save",
    payload,
  });

  return {
    filePath: pickCase(data, "filePath", "FilePath", ""),
  };
}

export async function deleteEntryTemplate(filePath: string): Promise<boolean> {
  return sendCommand<boolean>({
    action: "templates.delete",
    payload: { filePath },
  });
}
