import { defineStore } from "pinia";
import ajax from "@/plugins/ajax.js";
import { successAlert } from "@/components/Mudur-Ui-Kit/alert.js";

export const useApiRequestStore = defineStore("ApiRequestStore", {
  state: () => ({
    apiKey: window.gcargo.api_key || "",
  }),
  actions: {
    syncOptions: async () => {
      const response = await ajax.post("sync_options");
      successAlert({ message: "Ayarlar başarıyla senkronize edildi." });

      return response;
    },
    fixAddress: async (context) => {
      return await ajax.post("fix_address", { data: context });
    },
    createMpSeller: async (context) => {
      return await ajax.post("create_mp_seller", { data: context });
    },
    getPdf: async (contex) => {
      const endpoint =
        contex.type === "returned" ? "print_returned_barcode" : "print_barcode";
      const data = await ajax.post(endpoint, { data: contex.data });
      const pdfData = atob(data);
      const arrayBuffer = new Uint8Array(pdfData.length);

      for (let i = 0; i < pdfData.length; i++) {
        arrayBuffer[i] = pdfData.charCodeAt(i);
      }

      const blob = new Blob([arrayBuffer], { type: "application/pdf" });
      const url = URL.createObjectURL(blob);
      return url;
    },
  },
});
