import {defineStore} from 'pinia'
import {config} from '@/config'
import {useErrorStore} from "@/store/error.js";
import {useStageStore} from "@/store/stage.js";
import {usePropertySetsStore} from "@/store/propertySets.js";

export const useCountryStore = defineStore('country', {
    state() {
        return {
            countries: null,
            loading: false,
            query: null,
            selectedCountryId: null,
            selectedPeriodId: null,
            countryDetail: null,
        }
    },
    getters: {
        getCountries(state) {
            return state.countries;
        },
        getSelectedCountry(state) {
            return state.countryDetail;
        }

    },
    actions: {
        async setProperty(property) {
            if(this.getSelectedCountry === null) return;

            const prop = this.getSelectedCountry.properties.find(p => p.external_mapping_id === property.id);

            if((prop ?? null) === null) return;

            const url = `${config.backendUrl}/properties/country/${this.getSelectedCountry.iso_code}/${property.id}`;
            const body = { value: String(property.value)};

            await this.performRequest('PUT', url, body, false);

            prop.draft_value = property.reset ? null : property.value;

            const stage = useStageStore();
            await stage.checkStagedChanges();
        },
        async selectPeriod(periodId) {
            this.loading = true;
            this.countryDetail = null;
            this.selectedPeriodId = periodId;
            await this.loadCountryDetail();
            this.loading = false;
        },
        async selectCountry(countryId) {
            this.selectedCountryId = countryId;
            await this.loadCountryDetail();
        },
        async loadCountryDetail() {
            if(this.selectedCountryId == null) return;
            this.loading = true;

            const params = new URLSearchParams();
            if(this.selectedPeriodId !== null)
                params.append('property_set', this.selectedPeriodId);

            const url = `${config.backendUrl}/countries/${this.selectedCountryId}/${params.size === 0 ? '' : '?'}${params.toString()}`;
            this.countryDetail = await this.performRequest('GET', url, null);

            this.loading = false;
        },
        async setQuery(query) {
            this.query = query;
            await this.fetchCountryList();
        },
        async reload() {
            const stage = useStageStore();
            await stage.checkStagedChanges();
        },
        async fetchCountryList() {
            const params = new URLSearchParams();
            if (this.query !== null)
                params.append('filter', this.query);
            const url = `${config.backendUrl}/countries/all/${params.size === 0 ? '' : '?'}${params.toString()}`;
            this.countries = await this.performRequest('GET', url, null);
        },
        async performRequest(method, url, body, expectResponse = true) {

            const params = {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                }
            };

            if ((body ?? null) !== null) {
                params.body = JSON.stringify(body);
            }

            const request = {url: url, params: params};
            console.log("Request:", request);

            const response = await fetch(url, params
            ).catch(e => {
                const error = {
                    code: 'Network error.',
                    message: "Please check your internet connection.",
                    trace: null
                }

                console.error(error);
                const errorStore = useErrorStore();
                void errorStore.addError(error, {store: this, request: request});

                throw e;
            });

            let data = null;
            if (expectResponse) {
                data = await response.json().catch(e => {
                    const error = {
                        code: 'Malformed response',
                        message: "Malformed server response. Please contact support.",
                        trace: null
                    }

                    console.error(error);
                    const errorStore = useErrorStore();
                    void errorStore.addError(error, {store: this, request: request});
                    throw e;
                });

                if (!response.ok) {
                    const error = {
                        code: data.error.code,
                        title: data.error.title,
                        message: data.error.message,
                        trace: data.error.trace
                    }

                    console.error(error);
                    const errorStore = useErrorStore();
                    void errorStore.addError(error, {store: this, request: request});
                    throw new Error('Internal backend error');
                }
            } else {
                if (!response.ok) {

                    const data = await response.json().catch(e => {
                        const error = {
                            code: "Return code error " + response.status,
                            message: "Server returned wrong response code",
                            trace: null
                        }
                        console.error(error);
                        const errorStore = useErrorStore();
                        void errorStore.addError(error, {store: this, request: request});
                        throw new Error('Internal backend error');

                    });

                    const error = {
                        code: data.error.code,
                        title: data.error.title,
                        message: data.error.message,
                        trace: data.error.trace
                    }

                    console.error(error);
                    const errorStore = useErrorStore();
                    void errorStore.addError(error, {store: this, request: request});
                    throw new Error('Internal backend error');


                }
            }

            console.log("Response:", data);
            return data;
        }
    },

});