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


export const useAssistantStore = defineStore('assistant', {
    state: () => ({
        materials: [],
        suppliers: [],
        createEmpty: false,
        loading: false,
        error: null,
        pagination: {},
        query: {},
        premises: null
    }),
    getters: {
        count: state => state.materials.length * state.suppliers.length,
    },
    actions: {
        setCreateEmpty(createEmpty) {
            this.createEmpty = createEmpty;
        },
        async createPremises() {

            const url = `${config.backendUrl}/calculation/create/`;

            const materialIds = this.materials.map((material) => material.id);
            const supplierIds = this.suppliers.filter(s => s.id.startsWith('s')).map((supplier) => supplier.origId);
            const userSupplierIds = this.suppliers.filter(s => s.id.startsWith('u')).map((supplier) => supplier.origId);
            const jsonBody = JSON.stringify({ material: materialIds, supplier: supplierIds, user_supplier: userSupplierIds, createEmpty: this.createEmpty });

            console.log(`Creation body: ${jsonBody}`);

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

            const request = { url: url, params: params};

            const response = await fetch(url, params).catch(e => {
                this.error = {code: 'Network error.', message: "Please check your internet connection.", trace: null}
                console.error(this.error);
                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
                }
                console.error(this.error);
                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.premises = data;
            console.log(this.premises);


        },
        addSupplier(supplier) {
            const uid = `${supplier.is_user_node ? 'u' : 's'}${supplier.id}`

            if (!this.suppliers.some(s => s.id === uid)) {
                this.suppliers.push({
                    id: uid,
                    origId: supplier.id,
                    isUserSupplier: false,
                    name: supplier.name,
                    address: supplier.address,
                    iso: supplier.country['iso_code']
                })

            }
        },
        deleteMaterial(id) {
            const index = this.materials.findIndex(m => m.id === id);

            if (index !== -1) {
                this.materials.splice(index, 1);
            }
        },
        deleteSupplier(id) {
            const index = this.suppliers.findIndex(s => s.id === id);

            if (index !== -1) {
                this.suppliers.splice(index, 1);
            }
        },
        async getMaterialsAndSuppliers(query) {

            this.loading = true;
            this.empty = true
            this.materials = [];
            this.suppliers = [];


            const url = `${config.backendUrl}/calculation/search/`;

            console.log(`${url} with query ${query}`);

            const headers = new Headers();
            headers.append('search', encodeURIComponent(query));

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

            const response = await fetch(url, {
                method: 'GET',
                headers: headers
            }).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;
            }


            const newSuppliers = [];

            for (const supplier of data.supplier) {
                const newSupplier = {
                    id: `s${supplier.id}`,
                    origId: supplier.id,
                    isUserSupplier: false,
                    name: supplier.name,
                    address: supplier.address,
                    iso: supplier.country['iso_code']
                };
                newSuppliers.push(newSupplier);
            }


            for (const supplier of data.user_supplier) {
                const newSupplier = {
                    id: `u${supplier.id}`,
                    origId: supplier.id,
                    isUserSupplier: true,
                    name: supplier.name,
                    address: supplier.address,
                    iso: supplier.country['iso_code']
                };
                newSuppliers.push(newSupplier);

            }

            this.loading = false;
            this.materials = data.materials;
            this.suppliers = newSuppliers;


        }

    }
});
