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


export const useNodeStore = defineStore('node', {
    state: () => ({
        nodes: [],
        loading: false,
        empty: true,
        error: null,
        pagination: {},
        query: {},
    }),
    getters: {
        getById: (state) => {
            return (id) => state.nodes.find(p => p.id === id)
        }
    },
    actions: {
        async setQuery(query) {
            this.query = query;
            await this.loadNodes();
        },
        async loadNodes() {

            const params = new URLSearchParams();

            if (this.query.searchTerm)
                params.append('filter', this.query.searchTerm);

            if (this.query.nodeType)
                params.append('node_type', this.query.nodeType);

            if (this.query.includeUserNode)
                params.append('include_user_node', this.query.includeUserNode);

            const url = `${config.backendUrl}/nodes/search/${params.size === 0 ? '' : '?'}${params.toString()}`;

            const request = { url: url, params: {method: 'GET'}};

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

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

                throw e;
            });

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

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

                throw e;
            });

            if (!response.ok) {
                this.error = {code: data.error.code, title: data.error.title, message: data.error.message, trace: data.error.trace };
                this.loading = false;

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

                return;
            }

            this.loading = false;
            this.empty = data.length === 0;
            this.nodes = data;

        }
    }
});
