import http from "../http-common";

const listTemplates = () => {
  return http.get("/template-files");
};

const uploadTemplate = (key, file) => {
  const formData = new FormData();
  formData.append("file", file);
  const currentUser = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;
  const userName = currentUser?.name || "system";

  return http.post(`/template-files/${key}/upload`, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
      "x-user-name": userName,
    },
  });
};

const getTemplateFileUrl = (fileUrl) => {
  const baseUrl = http.defaults.baseURL || "";
  return `${baseUrl.replace("/api", "")}${fileUrl}`;
};

export const TemplateFileService = {
  listTemplates,
  uploadTemplate,
  getTemplateFileUrl,
};
