import { AxiosResponse } from "axios";
import recordAxiosInstance from "@/shared/services/recordAxiosInstance";
import { withHeaders } from "@/record-management/services/api/withHeaders";
import { take } from "lodash";
import { externalParam } from "@/external-portal/services/portalOutgoingService";

// --- Payloads ---
export interface LetterTemplatePayload {
  sincerelyText: string;
  body: string;
  subject: string;
  key: string;
  name: {
    am: string;
    en: string;
  };
  unitId: string;
  headerId?: string;
  footerId?: string;
}

export interface LetterTemplate extends LetterTemplatePayload {
  id: string;
  createdAt?: string;
  updatedAt?: string;
}

// --- Headers ---
export interface LetterTemplateHeaders {
  delegatorPositionId: string;
  currentProjectId: string;
}

export interface LetterTemplatesResponse {
  count: number;
  items: LetterTemplate[];
}

// --- GET: All templates under a unit ---
export const getTemplatesByUnitId = async (
  unitId: string,
  params: externalParam,
): Promise<AxiosResponse<LetterTemplatesResponse>> => {
  return recordAxiosInstance.get(`/record-templates/list/${unitId}`, {
    headers: withHeaders(),
    params,
  });
};

// --- GET: Template by ID ---
export const getTemplateById = async (
  id: string,
): Promise<AxiosResponse<LetterTemplate>> => {
  return recordAxiosInstance.get(`/record-templates/${id}`, {
    headers: withHeaders(),
  });
};

// --- POST: Create new template ---
export const createTemplate = async (
  data: LetterTemplatePayload,
): Promise<AxiosResponse<LetterTemplate>> => {
  return recordAxiosInstance.post(`/record-templates`, data, {
    headers: withHeaders(),
  });
};

// --- PUT: Update template ---
export const updateTemplate = async (
  id: string,
  data: LetterTemplatePayload,
): Promise<AxiosResponse<LetterTemplate>> => {
  return recordAxiosInstance.put(`/record-templates/${id}`, data, {
    headers: withHeaders(),
  });
};

// --- DELETE: Template by ID ---
export const deleteTemplate = async (
  id: string,
): Promise<AxiosResponse<void>> => {
  return recordAxiosInstance.delete(`/record-templates/${id}`, {
    headers: withHeaders(),
  });
};
