create table if not exists public.analytics_events (
  id uuid primary key default gen_random_uuid(),
  event_name text not null,
  event_source text not null check (event_source in ('web_app', 'api', 'stripe_webhook', 'system')),
  user_id uuid references public.users (id) on delete set null,
  workspace_id uuid references public.workspaces (id) on delete set null,
  plan_code text,
  addon_code text,
  resource text,
  amount numeric,
  currency text,
  metadata_json jsonb not null default '{}'::jsonb,
  occurred_at timestamptz not null default now(),
  created_at timestamptz not null default now()
);

create index if not exists analytics_events_occurred_at_idx on public.analytics_events (occurred_at desc);
create index if not exists analytics_events_event_name_idx on public.analytics_events (event_name);
create index if not exists analytics_events_workspace_id_idx on public.analytics_events (workspace_id);
create index if not exists analytics_events_plan_code_idx on public.analytics_events (plan_code);
