import { defineStore } from "pinia";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";
import type {
  CreateTemplateViewModel,
  TemplateViewModel,
  UpdateTemplateViewModel,
} from "@/viewmodels/admin/template.models";

export const useTemplateStore = defineStore("template", {
  state: () => {
    return {
      templates: [] as Array<TemplateViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchTemplates() {
      this.loading = "loading";
      http
        .get("/admin/template")
        .then((result) => {
          this.templates = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchTemplateById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/template/${id}`);
    },
    async createTemplate(template: CreateTemplateViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/template`, {
        template: template.template,
        description: template.description,
      });
      this.fetchTemplates();
      return result;
    },
    async updateActiveTemplate(template: UpdateTemplateViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/template/${template.id}`, {
        template: template.template,
        description: template.description,
        design: template.design,
        html: template.html,
      });
      this.fetchTemplates();
      return result;
    },
    async cloneTemplate(cloneId: number): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/template/clone`, {
        cloneId: cloneId,
      });
      this.fetchTemplates();
      return result;
    },
    async deleteTemplate(template: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/template/${template}`);
      this.fetchTemplates();
      return result;
    },
  },
});
