import { useCompanyStore } from '@/stores/companyStore';
import { useCallback } from 'react';
import type { Company } from '@/types/accounting';

/**
 * Hook for accessing and managing the current company context
 */
export function useCompany() {
  const activeCompany = useCompanyStore((state) => state.activeCompany);
  const companies = useCompanyStore((state) => state.companies);
  const isLoading = useCompanyStore((state) => state.isLoading);
  const setActiveCompany = useCompanyStore((state) => state.setActiveCompany);

  /**
   * Get the current company ID or throw if not set
   */
  const requireCompanyId = useCallback((): string => {
    if (!activeCompany) {
      throw new Error('No company selected. Please select a company first.');
    }
    return activeCompany.id;
  }, [activeCompany]);

  /**
   * Check if a company is selected
   */
  const hasCompany = !!activeCompany;

  /**
   * Switch to a different company
   */
  const switchCompany = useCallback(
    (companyId: string) => {
      const company = companies.find((c) => c.id === companyId);
      if (company) {
        setActiveCompany(company);
      }
    },
    [companies, setActiveCompany]
  );

  /**
   * Get company by ID
   */
  const getCompanyById = useCallback(
    (id: string): Company | undefined => {
      return companies.find((c) => c.id === id);
    },
    [companies]
  );

  return {
    // Current company
    company: activeCompany,
    companyId: activeCompany?.id,
    companyName: activeCompany?.name,

    // All companies
    companies,

    // State
    isLoading,
    hasCompany,

    // Actions
    requireCompanyId,
    switchCompany,
    getCompanyById,
  };
}
