import {defineStore} from 'pinia'
import {config} from '@/config'
import performRequest from "@/backend.js";

export const useCustomsStore = defineStore('customs', {
    state() {
        return {
            hsCodes: [],
            tariffInfo: null,
            loadingTariff: false,

        }
    },
    getters: {
        showWarning(state) {
            return function (countryId) {
                const info = state.tariffInfo?.find(t => t.countryId === countryId);

                if ((info ?? null) !== null) {
                    return info.default || info.measures?.length > 1;
                }

                return false;
            }
        },
        findByCountryId(state) {
            return function (countryId) {
                return state.tariffInfo?.find(t => t.countryId === countryId);
            }
        }
    },
    actions: {
        async findTariffRate(query) {
            this.loadingTariff = true;
            const url = `${config.backendUrl}/customs?hs_code=${query.hsCode}&country_ids=${query.countryIds}`;
            const resp = await performRequest(this, 'GET', url, null).catch(() => {
                this.tariffInfo = null;
                this.loadingTariff = false;
            })
            this.tariffInfo = resp.data;

            this.tariffInfo.forEach(info => info.measures.sort((m1, m2) => {  return parseInt(m1.code) - parseInt(m2.code); }));

            this.loadingTariff = false;
            return this.tariffInfo;
        },
        async findHsCode(query) {

            const url = `${config.backendUrl}/customs/search?hs_code=${query}`;
            const resp = await performRequest(this, 'GET', url, null);
            this.hsCodes = resp.data;
            return this.hsCodes;

        }
    }
});
