-- 043_analytics_events.sql
-- Generic Analytics Events Table for Job Worker
-- This table stores generic analytics events processed by the job worker

CREATE TABLE IF NOT EXISTS public.analytics_events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    event_name VARCHAR(100) NOT NULL,
    user_id UUID REFERENCES public.users(id) ON DELETE SET NULL,
    payload JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes for efficient querying
CREATE INDEX idx_analytics_events_name ON public.analytics_events(event_name);
CREATE INDEX idx_analytics_events_user_id ON public.analytics_events(user_id) WHERE user_id IS NOT NULL;
CREATE INDEX idx_analytics_events_created_at ON public.analytics_events(created_at DESC);

-- GIN index for JSONB payload queries
CREATE INDEX idx_analytics_events_payload_gin ON public.analytics_events USING GIN (payload);

-- Composite index for common queries (event_name + created_at)
CREATE INDEX idx_analytics_events_name_created_at ON public.analytics_events(event_name, created_at DESC);

COMMENT ON TABLE public.analytics_events IS 'Generic analytics events table for storing various application events processed by the job worker';
COMMENT ON COLUMN public.analytics_events.event_name IS 'Name of the event (e.g., track_play, user_login, file_upload)';
COMMENT ON COLUMN public.analytics_events.user_id IS 'ID of the user who triggered the event (nullable for anonymous events)';
COMMENT ON COLUMN public.analytics_events.payload IS 'JSON payload containing event-specific data';
COMMENT ON COLUMN public.analytics_events.created_at IS 'Timestamp when the event was created';

