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


export const useAssistantStore = defineStore('assistant', {
    state: () => ({
        materials: [],
        suppliers: [],
        createEmpty: false,
        loading: false,
        error: null,
        pagination: {},
        query: {},
    }),
    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 body = {
                material: materialIds,
                supplier: supplierIds,
                user_supplier: userSupplierIds,
                from_scratch: this.createEmpty
            };

            const resp = await performRequest(this, 'POST', `${config.backendUrl}/calculation/create/`, body, true);

            return resp.data.map(p => p.id);


        },
        reset() {
            this.materials = [];
            this.suppliers = [];
            this.createEmpty = false;
            this.loading = false;
            this.error = null;
            this.pagination = {};
            this.query = {};
        },
        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/`;

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

            try {
                const resp = await performRequest(this, 'GET', `${config.backendUrl}/calculation/search/?search=${encodeURIComponent(query)}`, null, true);
                const data = resp.data;

                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;

            } catch (e) {

            }





        }

    }
});
