-- =============================================================
-- AGENCIA LEÓN - Esquema del panel de gestión
-- Ejecutar en: Supabase Dashboard > SQL Editor > New query
-- =============================================================

-- -------------------------------------------------------------
-- 1. TRACKING DE VISITAS (estadísticas propias, en tiempo real)
-- -------------------------------------------------------------

create table if not exists sesiones (
  id uuid primary key default gen_random_uuid(),
  inicio timestamptz not null default now(),
  ultima_actividad timestamptz not null default now(),
  origen text not null default 'directo',        -- instagram | google | directo | otro
  dispositivo text not null default 'escritorio' -- movil | tablet | escritorio
);

create table if not exists eventos (
  id bigint generated always as identity primary key,
  sesion_id uuid not null references sesiones(id) on delete cascade,
  tipo text not null,   -- pageview | seccion | click_whatsapp | click_instagram
  valor text,           -- ej: nombre de la sección vista
  created_at timestamptz not null default now()
);

create index if not exists eventos_created_idx on eventos (created_at);
create index if not exists eventos_tipo_idx on eventos (tipo);
create index if not exists sesiones_actividad_idx on sesiones (ultima_actividad);

-- -------------------------------------------------------------
-- 2. TESTIMONIOS (novios envían, dueño aprueba)
-- -------------------------------------------------------------

create table if not exists testimonios (
  id uuid primary key default gen_random_uuid(),
  nombres text not null,          -- ej: "Camila y Luis"
  comuna text,
  centro_eventos text,            -- dónde se realizó el matrimonio (opcional)
  estrellas int not null default 5 check (estrellas between 1 and 5),
  mensaje text not null check (char_length(mensaje) <= 600),
  estado text not null default 'pendiente', -- pendiente | aprobado | rechazado
  created_at timestamptz not null default now()
);

-- -------------------------------------------------------------
-- 3. COTIZACIONES (formulario de la web)
-- -------------------------------------------------------------

create table if not exists cotizaciones (
  id uuid primary key default gen_random_uuid(),
  nombre text not null,
  telefono text,
  fecha_evento date,
  lugar text,
  invitados int,
  servicios text,
  mensaje text,
  estado text not null default 'nueva', -- nueva | contactada | cerrada
  created_at timestamptz not null default now()
);

-- -------------------------------------------------------------
-- 4. CONTENIDOS EDITABLES (textos y paquetes de la web)
-- -------------------------------------------------------------

create table if not exists contenidos (
  clave text primary key,  -- ej: 'paquetes', 'quienes_somos', 'hero'
  valor jsonb not null,
  actualizado timestamptz not null default now()
);

-- -------------------------------------------------------------
-- 5. FECHAS OCUPADAS (calendario de disponibilidad)
-- -------------------------------------------------------------

create table if not exists fechas_ocupadas (
  fecha date primary key,
  nota text
);

-- -------------------------------------------------------------
-- 6. GALERÍA (metadatos; los archivos van en Storage)
-- -------------------------------------------------------------

create table if not exists galeria (
  id uuid primary key default gen_random_uuid(),
  storage_path text not null,
  tipo text not null default 'foto', -- foto | video
  titulo text,
  instagram_url text, -- link a la publicación de Instagram (opcional)
  orden int not null default 0,
  visible boolean not null default true,
  created_at timestamptz not null default now()
);

-- =============================================================
-- SEGURIDAD (RLS)
-- Visitantes anónimos: solo lo mínimo. Dueño autenticado: todo.
-- =============================================================

alter table sesiones enable row level security;
alter table eventos enable row level security;
alter table testimonios enable row level security;
alter table cotizaciones enable row level security;
alter table contenidos enable row level security;
alter table fechas_ocupadas enable row level security;
alter table galeria enable row level security;

-- Tracking: el visitante crea su sesión y registra eventos, nada más
create policy anon_insert_sesiones on sesiones for insert to anon with check (true);
create policy anon_update_sesiones on sesiones for update to anon using (true) with check (true);
create policy anon_insert_eventos on eventos for insert to anon with check (true);

-- Testimonios: el visitante envía (siempre queda pendiente) y ve solo aprobados
create policy anon_insert_testimonios on testimonios for insert to anon
  with check (estado = 'pendiente');
create policy anon_select_testimonios on testimonios for select to anon
  using (estado = 'aprobado');

-- Cotizaciones: el visitante solo envía
create policy anon_insert_cotizaciones on cotizaciones for insert to anon with check (true);

-- Contenidos, fechas y galería: el visitante solo lee
create policy anon_select_contenidos on contenidos for select to anon using (true);
create policy anon_select_fechas on fechas_ocupadas for select to anon using (true);
create policy anon_select_galeria on galeria for select to anon using (visible = true);

-- Dueño autenticado: acceso total a todo
create policy auth_all_sesiones on sesiones for all to authenticated using (true) with check (true);
create policy auth_all_eventos on eventos for all to authenticated using (true) with check (true);
create policy auth_all_testimonios on testimonios for all to authenticated using (true) with check (true);
create policy auth_all_cotizaciones on cotizaciones for all to authenticated using (true) with check (true);
create policy auth_all_contenidos on contenidos for all to authenticated using (true) with check (true);
create policy auth_all_fechas on fechas_ocupadas for all to authenticated using (true) with check (true);
create policy auth_all_galeria on galeria for all to authenticated using (true) with check (true);

-- =============================================================
-- TIEMPO REAL (el panel se actualiza solo al llegar actividad)
-- =============================================================

alter publication supabase_realtime add table sesiones;
alter publication supabase_realtime add table eventos;
alter publication supabase_realtime add table cotizaciones;
alter publication supabase_realtime add table testimonios;
