-- ============================================================
-- Gustito Express — MEDICION DE LA LANDING (primera parte propia).
-- Tabla de eventos anonimos (sin datos personales): visitas y clicks
-- clave de gustitoxpress.app. Cualquiera puede INSERTAR (con lista
-- blanca de eventos via CHECK), NADIE puede leer por la API; el embudo
-- lo ve solo el fundador con la RPC ceo_embudo_web.
-- ============================================================

create table if not exists public.eventos_web (
  id           bigint generated always as identity primary key,
  evento       text not null check (evento in (
                 'visita','click_registro','click_entrar','click_vitrina',
                 'click_whatsapp','click_demo','cuenta_creada')),
  pantalla     text,
  origen       text,
  utm_source   text,
  utm_medium   text,
  utm_campaign text,
  sesion       uuid,
  creado_en    timestamptz not null default now()
);
create index if not exists idx_eventos_web_evento_fecha on public.eventos_web (evento, creado_en);
alter table public.eventos_web enable row level security;

-- Insertar: publico (la landing no tiene sesion). Leer: nadie via REST.
create policy eventos_web_insert_publico on public.eventos_web
  for insert to anon, authenticated
  with check (true);

grant insert on public.eventos_web to anon, authenticated;

-- ---- Embudo para el Panel del Fundador ----
create or replace function public.ceo_embudo_web(p_dias int default 7)
returns jsonb
language plpgsql stable security definer set search_path to 'public'
as $function$
declare
  v jsonb;
  v_desde timestamptz := now() - make_interval(days => greatest(1, coalesce(p_dias, 7)));
begin
  if not exists (select 1 from public.perfiles where id = auth.uid() and es_fundador) then
    raise exception 'Solo el fundador puede ver esto';
  end if;

  select jsonb_build_object(
    'dias',            greatest(1, coalesce(p_dias, 7)),
    'visitas',         (select count(*) from public.eventos_web where evento = 'visita' and creado_en >= v_desde),
    'click_registro',  (select count(*) from public.eventos_web where evento = 'click_registro' and creado_en >= v_desde),
    'click_entrar',    (select count(*) from public.eventos_web where evento = 'click_entrar' and creado_en >= v_desde),
    'click_vitrina',   (select count(*) from public.eventos_web where evento = 'click_vitrina' and creado_en >= v_desde),
    'click_whatsapp',  (select count(*) from public.eventos_web where evento = 'click_whatsapp' and creado_en >= v_desde),
    'click_demo',      (select count(*) from public.eventos_web where evento = 'click_demo' and creado_en >= v_desde),
    'cuentas_creadas', (select count(*) from public.eventos_web where evento = 'cuenta_creada' and creado_en >= v_desde),
    'negocios_creados',    (select count(*) from public.restaurantes where creado_en >= v_desde),
    'negocios_publicados', (select count(*) from public.restaurantes where publicado and creado_en >= v_desde),
    'origenes', (
      select coalesce(jsonb_agg(jsonb_build_object('origen', o, 'n', n) order by n desc), '[]'::jsonb)
      from (
        select coalesce(nullif(trim(coalesce(utm_source, origen)), ''), 'directo') o, count(*) n
        from public.eventos_web
        where evento = 'visita' and creado_en >= v_desde
        group by 1 order by n desc limit 8
      ) t
    )
  ) into v;
  return v;
end;
$function$;
grant execute on function public.ceo_embudo_web(int) to authenticated;
