import { useQuery } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';

export interface TechnicalSpecification {
  id: string;
  entity_type: 'ride' | 'ride_model';
  entity_id: string;
  spec_name: string;
  spec_value: string;
  spec_unit?: string | null;
  category?: string | null;
  display_order: number;
  created_at: string;
}

export function useTechnicalSpecifications(
  entityType: 'ride' | 'ride_model',
  entityId: string | undefined
) {
  return useQuery({
    queryKey: ['technical-specifications', entityType, entityId],
    queryFn: async () => {
      if (!entityId) return [];
      
      const tableName = entityType === 'ride' 
        ? 'ride_technical_specifications' 
        : 'ride_model_technical_specifications';
      const idColumn = entityType === 'ride' ? 'ride_id' : 'ride_model_id';
      
      if (entityType === 'ride') {
        const { data, error } = await supabase
          .from('ride_technical_specifications')
          .select('*')
          .eq('ride_id', entityId)
          .order('display_order');
        
        if (error) throw error;
        
        return (data || []).map((spec) => ({
          id: spec.id,
          entity_type: 'ride' as const,
          entity_id: entityId,
          spec_name: spec.spec_name,
          spec_value: spec.spec_value,
          spec_unit: spec.unit || null,
          category: spec.category || null,
          display_order: spec.display_order,
          created_at: spec.created_at,
        })) as TechnicalSpecification[];
      } else {
        const { data, error } = await supabase
          .from('ride_model_technical_specifications')
          .select('*')
          .eq('ride_model_id', entityId)
          .order('display_order');
        
        if (error) throw error;
        
        return (data || []).map((spec) => ({
          id: spec.id,
          entity_type: 'ride_model' as const,
          entity_id: entityId,
          spec_name: spec.spec_name,
          spec_value: spec.spec_value,
          spec_unit: spec.unit || null,
          category: spec.category || null,
          display_order: spec.display_order,
          created_at: spec.created_at,
        })) as TechnicalSpecification[];
      }
    },
    enabled: !!entityId
  });
}
