<template>
    <div class="row m-b-15 parentContainer">
        <div class="col" v-if="authStore.getUserId">
            <list-component :section="section" :endpoint="route('api.milestone.list')">
                <template #list="{ data }">
                    <milestone-single-item-component :section="section" :data="data" :options-milestone-name="optionsMilestoneName"></milestone-single-item-component>
                </template>
            </list-component>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, watch } from 'vue';
import route from '@/general/functions/router';
import { useAuthStore } from '@/stores/auth';
import { useQueueStore } from '@/stores/queue';
import { useUiStore } from '@/stores/ui';
import { useCrudStore } from '@/stores/crud';

interface Props {
    section: string;
    optionsMilestoneName: any[];
}

const props = defineProps<Props>();
const authStore = useAuthStore();
const queueStore = useQueueStore();
const uiStore = useUiStore();
const crudStore = useCrudStore();

const section = props.section;
const optionsMilestoneName = props.optionsMilestoneName;
const subSection = 'rewardListSection';
const endpoint = route('api.reward.list');
const options = { is_active: true };
const valueColumn = 'id';
const labelColumn = ['name', 'milestones'];

if (!queueStore.isInQueue(subSection)) {
    queueStore.updateListQueue({ name: subSection });
}

const pendingQueue = computed(() => queueStore.isInCompleteQueue(subSection));

const preFetchDataForChildComponent = async () => {
    uiStore.toggleLoading(subSection, true);
    const response = await crudStore.crudRequest({ endpoint: `${endpoint}?filters=${JSON.stringify(options)}`, method: 'get' });
    const success = response.ok;
    const parsed = await response.json();
    if (!success) {
        uiStore.toggleLoading(subSection, false);
        return;
    }

    const mappedList = parsed.payload.data.map((value: any) => ({
        id: !isNaN(value[valueColumn]) ? parseInt(value[valueColumn], 10) : value[valueColumn],
        text: labelColumn.map((label) => (typeof value[label] === 'object' ? value[label].map((obj: any) => obj.name) : value[label])).join(': ')
    }));

    queueStore.updateListQueue({ name: `original_${subSection}` });
    queueStore.setListComplete({ name: `original_${subSection}`, data: parsed.payload.data });
    queueStore.setListComplete({ name: subSection, data: mappedList });
    uiStore.toggleLoading(subSection, false);
};

watch(pendingQueue, (newVal) => {
    if (newVal) preFetchDataForChildComponent();
});
</script>
