import { useEffect, useState } from "react";
import { listMaster, MASTER_TABLES } from "../services/masterApi.js";

export default function useMasterData() {
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    let mounted = true;
    async function load() {
      setLoading(true);
      setError("");
      try {
        const results = await Promise.allSettled(
          MASTER_TABLES.map(async (t) => [t, await listMaster(t)])
        );
        const entries = [];
        const failures = [];
        results.forEach((result, index) => {
          const table = MASTER_TABLES[index];
          if (result.status === "fulfilled") {
            entries.push(result.value);
            return;
          }
          failures.push(table);
        });
        if (mounted) {
          setData(Object.fromEntries(entries));
          if (failures.length) {
            setError(
              failures.length === 1
                ? `Could not load lookup table: ${failures[0]}.`
                : `Could not load lookup tables: ${failures.join(", ")}.`
            );
          }
        }
      } catch (err) {
        if (mounted) setError(err?.response?.data?.message || err.message);
      } finally {
        if (mounted) setLoading(false);
      }
    }
    load();
    return () => {
      mounted = false;
    };
  }, []);

  return { data, loading, error };
}
