import { defineStore } from 'pinia';
import { useCrudStore } from './crud';

export interface QueueSingleItem {
    name: string;
    page: number;
    filters?: any;
    complete: boolean;
    data: any[];
}

export const useQueueStore = defineStore('queue', {
    state: () => ({
        queue: [] as QueueSingleItem[]
    }),
    getters: {
        isInQueue: (state) => (name: string): boolean => {
            const list = state.queue.find(item => item.name === name);
            return !!list;
        },
        isInCompleteQueue: (state) => (name: string): boolean => {
            const list = state.queue.find(item => item.name === name);
            return list ? !list.complete : false;
        },
        getListDetails: (state) => (name: string): QueueSingleItem => {
            return state.queue.find(item => item.name === name) || {
                name,
                page: 1,
                filters: {},
                complete: false,
                data: []
            };
        },
        getListData: (state) => (name: string): any[] => {
            const list = state.queue.find(item => item.name === name);
            const isComplete = list ? list.complete : false;
            return isComplete && list ? list.data : (list ? list.data : []);
        },
        getSelectableList: (state) => (name: string): any[] => {
            const list = state.queue.find(item => item.name === name);
            return list ? list.data : [];
        }
    },
    actions: {
        normalizeListFilters(filters?: Record<string, any>) {
            const normalizedFilters = { ...(filters ?? {}) };

            normalizedFilters.per_page = normalizedFilters.per_page !== undefined ? normalizedFilters.per_page : 10;
            normalizedFilters.order_by = normalizedFilters.order_by !== undefined ? normalizedFilters.order_by : {
                column: 'id',
                DESC: true
            };

            return normalizedFilters;
        },

        updateListQueue(payload: { name: string; page?: number; filters?: any }) {
            const normalizedFilters = this.normalizeListFilters(payload.filters);
            const page = payload.page ?? 1;
            const list = this.queue.find(item => item.name === payload.name);
            if (list) {
                Object.assign(list, { page, filters: normalizedFilters, complete: false });
            } else {
                this.queue.push({
                    name: payload.name,
                    page,
                    filters: normalizedFilters,
                    complete: false,
                    data: []
                });
            }
        },

        reloadList(payload: { name: string }) {
            if (this.isInQueue(payload.name)) {
                const list = this.queue.find(item => item.name === payload.name);
                if (list) {
                    list.complete = false;
                }
            } else {
                this.updateListQueue({ name: payload.name, page: 1, filters: {} });
            }
        },

        setListComplete(payload: { name: string; data: any[] }) {
            const list = this.queue.find(item => item.name === payload.name);
            if (list) {
                list.complete = true;
                list.data = payload.data;
            } else {
                this.queue.push({ name: payload.name, page: 1, complete: true, data: payload.data });
            }
        },

        async fetchSelectable(payload: { section: string; endpoint: string }) {
            if (!this.isInQueue(payload.section)) {
                this.updateListQueue({ name: payload.section });
                const crudStore = useCrudStore();
                const response = await crudStore.crudRequest({ endpoint: payload.endpoint, method: 'get' });
                if (response.ok) {
                    const data = await response.json();
                    this.setListComplete({ name: payload.section, data: data.payload.data });
                }
            }
        }
    }
});
