import { computed, reactive, watch } from 'vue';

interface OpenAccordions {
    [key: number]: string | undefined;
}

export const useParticipantError = (form: any) => {
    const openAccordions = reactive<OpenAccordions>({});

    const participantErrorKeys = computed(() => {
        const errorKeys = new Set<string>();

        Object.keys(form.value.errors)
            .filter((key) => key.startsWith('participants.'))
            .forEach((key) => {
                const match = key.match(/^participants\.(\d+)\./);
                if (match) {
                    errorKeys.add(`participant-${match[1]}`);
                }
            });

        return Array.from(errorKeys);
    });

    function getErrorParticipant(index: number, key: any) {
        return form.value.errors[`participants.${index}.${key}`];
    }

    watch(participantErrorKeys, (newKeys) => {
        newKeys.forEach((key) => {
            const index = parseInt(key.split('-')[1], 10);
            openAccordions[index] = key || '';
        });
    });

    return {
        openAccordions,
        participantErrorKeys,
        getErrorParticipant,
    };
};
