import {defineStore} from 'pinia'
import {config} from '@/config'
import {useNotificationStore} from "@/store/notification.js";
import { useStageStore } from './stage.js'
import performRequest from "@/backend.js";

export const useValidityPeriodStore = defineStore('validityPeriod', {
    state() {
        return {
            periods: null,
            selectedPeriod: null,
        }
    },
    getters: {
        getPeriods(state) {
            return state.periods;
        },
        getCurrentPeriodId(state) {
            if (state.periods === null)
                return null;

            for (const period of state.periods) {
                if (period.state === "VALID")
                    return period.id;
            }
        },
        getSelectedPeriod(state) {
            return state.selectedPeriod;
        },
        getPeriodState(state) {
            return function(periodId) {
                if (state.periods === null)
                    return null;

                return state.periods.find(p => p.id === periodId)?.state;
            }
        }
    },
    actions: {
        setSelectedPeriod(periodId) {
            this.selectedPeriod = periodId;
        },
        async invalidate() {

            const url = `${config.backendUrl}/rates/periods/${this.getSelectedPeriod}/`;
            this.periods = await performRequest(this,'DELETE', url, null, false);

            await this.reload();

        },
        async loadPeriods() {
            this.loading = true;
            const url = `${config.backendUrl}/rates/periods`;
            const data = await performRequest(this,'GET', url, null);
            this.periods = data.data;
            this.selectedPeriod = this.getCurrentPeriodId;
            this.loading = false;
        }
    }
});