import { useState, useEffect, useCallback } from 'react';
import api from '../services/api';

export function useCashSession() {
  const [session, setSession] = useState<{ isOpen: boolean; data: any | null }>({
    isOpen: false,
    data: null
  });
  const [loading, setLoading] = useState(true);

  const checkStatus = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get('/cashsessions/status');
      setSession({
        isOpen: res.data.isOpen,
        data: res.data.session
      });
    } catch (error) {
      console.error("Error al verificar estado de caja", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    checkStatus();
  }, [checkStatus]);

  return { session, loading, refreshSession: checkStatus };
}