/**
 * Hook for premises (child tenants) management
 */

import { useQuery, UseQueryResult } from '@tanstack/react-query';
import { tenantService } from '../services/tenant';
import type { TenantResponse } from '../types/tenant';

export interface PremisesFilters {
  search?: string;
  status?: 'active' | 'inactive' | '';
}

export interface PremisesStats {
  total: number;
  active: number;
  inactive: number;
}

/**
 * Get all child tenants (premises) for a parent tenant
 */
export const usePremises = (
  parentTenantId: string,
  filters?: PremisesFilters,
  options?: { enabled?: boolean }
): UseQueryResult<TenantResponse[]> => {
  return useQuery({
    queryKey: ['premises', parentTenantId, filters],
    queryFn: async () => {
      const response = await tenantService.getChildTenants(parentTenantId);

      let filtered = response;

      // Apply search filter
      if (filters?.search) {
        const searchLower = filters.search.toLowerCase();
        filtered = filtered.filter(tenant =>
          tenant.name.toLowerCase().includes(searchLower) ||
          tenant.city?.toLowerCase().includes(searchLower)
        );
      }

      // Apply status filter
      if (filters?.status === 'active') {
        filtered = filtered.filter(tenant => tenant.is_active);
      } else if (filters?.status === 'inactive') {
        filtered = filtered.filter(tenant => !tenant.is_active);
      }

      return filtered;
    },
    staleTime: 60000, // 1 min cache
    enabled: (options?.enabled ?? true) && !!parentTenantId,
  });
};

/**
 * Get premises statistics
 */
export const usePremisesStats = (
  parentTenantId: string,
  options?: { enabled?: boolean }
): UseQueryResult<PremisesStats> => {
  return useQuery({
    queryKey: ['premises', 'stats', parentTenantId],
    queryFn: async () => {
      const response = await tenantService.getChildTenants(parentTenantId);

      return {
        total: response.length,
        active: response.filter(t => t.is_active).length,
        inactive: response.filter(t => !t.is_active).length,
      };
    },
    staleTime: 60000,
    enabled: (options?.enabled ?? true) && !!parentTenantId,
  });
};
