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

/**
 * Fetches CPAS score, 90-day violation type counts, and full history
 * for a given employeeId. Re-fetches whenever employeeId changes.
 */
export default function useEmployeeIntelligence(employeeId) {
    const [score,         setScore]         = useState(null);
    const [counts90,      setCounts90]      = useState({});   // { violation_type: count } 90-day
    const [countsAllTime, setCountsAllTime] = useState({});   // { violation_type: { count, max_points_used } }
    const [history,       setHistory]       = useState([]);
    const [loading,       setLoading]       = useState(false);

    useEffect(() => {
        if (!employeeId) {
            setScore(null);
            setCounts90({});
            setCountsAllTime({});
            setHistory([]);
            return;
        }

        setLoading(true);
        Promise.all([
            axios.get(`/api/employees/${employeeId}/score`),
            axios.get(`/api/employees/${employeeId}/violation-counts`),
            axios.get(`/api/employees/${employeeId}/violation-counts/alltime`),
            axios.get(`/api/violations/employee/${employeeId}?limit=20`),
        ]).then(([scoreRes, counts90Res, allTimeRes, historyRes]) => {
            setScore(scoreRes.data);
            setCounts90(counts90Res.data);
            setCountsAllTime(allTimeRes.data);
            setHistory(historyRes.data);
        }).catch(console.error)
          .finally(() => setLoading(false));
    }, [employeeId]);

    return { score, counts90, countsAllTime, history, loading };
}
