import { supabase } from '@/supabase';

export interface AnalyticsEvent {
    event_name: string;
    entity_type?: 'business' | 'shuttle' | 'coupon' | 'stop' | 'route' | 'taxi' | 'system' | 'other';
    entity_id?: string; // The ID of the specific entity
    entity_name?: string; // Optional name for easier querying
    screen_name?: string; // Optional screen name
    properties?: Record<string, any>;
}

export const analyticsService = {
    /**
     * Logs an action or event to the analytics_events table.
     */
    async logEvent(event: AnalyticsEvent) {
        try {
            const { data: userData } = await supabase.auth.getUser();

            const payload = {
                event_name: event.event_name,
                entity_type: event.entity_type || 'system',
                entity_id: event.entity_id || 'none',
                entity_name: event.entity_name,
                properties: event.properties || {},
                user_id: userData?.user ? userData.user.id : null
            };

            const { error } = await supabase
                .from('analytics_events')
                .insert(payload);

            if (error) {
                console.warn('Analytics logging failed:', error);
            }
        } catch (e) {
            console.warn('Failed to dispatch analytics event:', e);
        }
    },

    /**
     * Gets aggregated statistics for the Dashboard.
     * Can be fleshed out with RPCs later if calculations are too heavy.
     */
    async getDashboardStats() {
        return null;
    }
};
