import axios from "axios";
import { defineStore } from "pinia";
import appService from "../services/appService";

export const useTransactionStore = defineStore("transaction", {
    state: () => ({
        lists: [],
        page: {},
        pagination: [],
        temp: {
            temp_id: null,
            isEditing: false,
        },
    }),
    actions: {
        fetchLists: function (payload) {
            return new Promise((resolve, reject) => {
                let url = "admin/transaction";
                if (payload) {
                    url = url + appService.requestHandler(payload);
                }
                axios
                    .get(url)
                    .then((res) => {
                        if (
                            typeof payload.pinia === "undefined" ||
                            payload.pinia === true
                        ) {
                            this.lists = res.data.data;
                            this.pagination = res.data;
                            if (
                                typeof res.data.meta !== "undefined" &&
                                res.data.meta !== null
                            ) {
                                this.page = {
                                    from: res.data.meta.from,
                                    to: res.data.meta.to,
                                    total: res.data.meta.total,
                                };
                            }
                        }
                        resolve(res);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        export: function (context, payload) {
            return new Promise((resolve, reject) => {
                let url = "admin/transaction/export";
                if (payload) {
                    url = url + appService.requestHandler(payload);
                }
                axios
                    .get(url, { responseType: "blob" })
                    .then((res) => {
                        resolve(res);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
    },
});
