import { AlertItem } from "../Shared/Alert";

const validateTrueFalseQuestions = (
    questions: {
        id: string;
        prompt: string;
        solution?: string;
    }[],
    setAlerts: React.Dispatch<React.SetStateAction<AlertItem[]>>
): boolean => {
    let hasErrors = false;
    
    const emptyPrompts = questions.filter(q => !q.prompt.trim());
    if (emptyPrompts.length > 0) {
        hasErrors = true;
        setAlerts(prev => {
            const filteredAlerts = prev.filter(alert => !alert.tag?.startsWith('empty-prompt'));
            return [...filteredAlerts, ...emptyPrompts.map(q => ({
                variant: "error" as const,
                tag: `empty-prompt-${q.id}`,
                description: `Question ${q.id} has an empty prompt`
            }))];
        });
    } else {
        setAlerts(prev => prev.filter(alert => !alert.tag?.startsWith('empty-prompt')));
    }

    const missingSolutions = questions.filter(q => q.solution === undefined);
    if (missingSolutions.length > 0) {
        hasErrors = true;
        setAlerts(prev => {
            const filteredAlerts = prev.filter(alert => !alert.tag?.startsWith('missing-solution'));
            return [...filteredAlerts, ...missingSolutions.map(q => ({
                variant: "error" as const,
                tag: `missing-solution-${q.id}`,
                description: `Question ${q.id} is missing a solution`
            }))];
        });
    } else {
        setAlerts(prev => prev.filter(alert => !alert.tag?.startsWith('missing-solution')));
    }

    return !hasErrors;
};

export default validateTrueFalseQuestions;
