﻿import { useState, useEffect } from 'react';

interface ClotureInfo {
    cloture: boolean;
    details: {
        mois_annee: string;
        date_debut: string;
        date_fin: string;
        campus: string | null;
        commentaire: string | null;
    } | null;
}

interface Cloture {
    id: number;
    mois_annee: string;
    date_debut: string;
    date_fin: string;
    campus: string | null;
    commentaire: string | null;
}

export const useClotureCheck = () => {
    const [clotures, setClotures] = useState<Cloture[]>([]);

    // Charger toutes les clôtures au démarrage
    useEffect(() => {
        fetch('/api/clotures')
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    setClotures(data.clotures);
                }
            })
            .catch(err => console.error('Erreur chargement clôtures:', err));
    }, []);

    const isDateCloturee = (dateString: string, campus?: string): boolean => {
        const date = new Date(dateString);

        return clotures.some(cloture => {
            const dateDebut = new Date(cloture.date_debut);
            const dateFin = new Date(cloture.date_fin);

            // Vérifier si la date est dans la période
            const dateInPeriod = date >= dateDebut && date <= dateFin;

            // Vérifier le campus si spécifié
            const campusMatch = !cloture.campus || !campus || cloture.campus === campus;

            return dateInPeriod && campusMatch;
        });
    };

    const getClotureDetails = (dateString: string, campus?: string): Cloture | null => {
        const date = new Date(dateString);

        return clotures.find(cloture => {
            const dateDebut = new Date(cloture.date_debut);
            const dateFin = new Date(cloture.date_fin);
            const dateInPeriod = date >= dateDebut && date <= dateFin;
            const campusMatch = !cloture.campus || !campus || cloture.campus === campus;

            return dateInPeriod && campusMatch;
        }) || null;
    };

    return { isDateCloturee, getClotureDetails, clotures };
};