<template>
    <select-component
        :disableOnFetch="props.disableOnFetch"
        :options="queueStore.getSelectableList(props.section)"
        :modelValue="props.modelValue"
        @update:modelValue="(val: any) => $emit('update:modelValue', val)"
    />
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { useQueueStore } from '@/stores/queue';
import { useCrudStore } from '@/stores/crud';

interface Props {
    modelValue?: any;
    section: string;
    endpoint: string;
    labelColumn: string[];
    valueColumn: string;
    disableOnFetch?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
    disableOnFetch: false
});

defineEmits(['update:modelValue']);

const queueStore = useQueueStore();
const crudStore = useCrudStore();

onMounted(async () => {
    if (!queueStore.isInQueue(props.section)) {
        queueStore.updateListQueue({ name: props.section });

        try {
            const response = await crudStore.crudRequest({
                endpoint: props.endpoint,
                method: 'get'
            });

            if (response.ok) {
                const result = await response.json();
                const rawData = result.payload.data;
                const dataArray = Array.isArray(rawData) ? rawData : Object.values(rawData || {});

                // Dynamic mapping logic
                const mappedList = dataArray.map((item: any) => {
                    const value = item[props.valueColumn];
                    const id = !isNaN(value) ? parseInt(value) : value;

                    const text = props.labelColumn.map((label) => {
                        return item[label];
                    }).join(': ');

                    return { id, text };
                });

                // Store both original and mapped lists
                queueStore.updateListQueue({ name: 'original_' + props.section });
                queueStore.setListComplete({
                    name: 'original_' + props.section,
                    data: dataArray
                });

                queueStore.setListComplete({
                    name: props.section,
                    data: mappedList
                });
            }
        } catch (error) {
            console.error('Error fetching selectable data:', error);
        }
    }
});
</script>


