import { defineStore } from "pinia";
import axios from 'axios'
export const useAdministratorAddressStore = defineStore("administratorAddress", {
    state: () => ({
        lists: [],
        temp: {
            temp_id: null,
            isEditing: false,
        },
    }),
    actions: {
        fetchLists: function (payload) {
            return new Promise((resolve, reject) => {
                axios.get(`admin/administrator/address/${payload.user_id}`).then((res) => {
                    this.lists = res.data.data;
                    resolve(res);
                }).catch((err) => {
                    reject(err);
                });
            });
        },
        save: function (payload) {
            return new Promise((resolve, reject) => {
                let method = axios.post;
                let url = `/admin/administrator/address/${payload.user_id}`;
                if (this.temp.isEditing) {
                    method = axios.put;
                    url = `/admin/administrator/address/${payload.user_id}/${this.temp.temp_id}`;
                }
                method(url, payload).then(res => {
                    this.addressList = res.data.data;
                    this.temp.temp_id = null;
                    this.temp.isEditing = false;
                        resolve(res);
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        },
        setTemp(payload) {
            this.temp.temp_id = payload;
            this.temp.isEditing = true;
        },
        resetTemp() {
            this.temp.temp_id = null;
            this.temp.isEditing = false;
        },        
    },
});
