create table if not exists public.sessoes_vsl (
  id uuid default uuid_generate_v4() primary key,
  usuario_id uuid references public.profiles(id) on delete cascade,
  titulo text not null default 'Nova VSL',
  status text default 'entrevista' check (status in ('entrevista','gerando','concluida')),
  dados_coletados jsonb default '{}',
  criado_em timestamptz default now(),
  atualizado_em timestamptz default now()
);

create table if not exists public.mensagens_vsl (
  id uuid default uuid_generate_v4() primary key,
  sessao_id uuid references public.sessoes_vsl(id) on delete cascade,
  role text not null check (role in ('user','assistant')),
  content text not null,
  criado_em timestamptz default now()
);

alter table public.sessoes_vsl enable row level security;
alter table public.mensagens_vsl enable row level security;

create policy "Usuario ve suas sessoes" on public.sessoes_vsl for select using (auth.uid() = usuario_id);
create policy "Usuario cria sessoes" on public.sessoes_vsl for insert with check (auth.uid() = usuario_id);
create policy "Usuario atualiza sessoes" on public.sessoes_vsl for update using (auth.uid() = usuario_id);
create policy "Usuario deleta sessoes" on public.sessoes_vsl for delete using (auth.uid() = usuario_id);

create policy "Usuario ve mensagens" on public.mensagens_vsl for select using (
  exists (select 1 from public.sessoes_vsl s where s.id = sessao_id and s.usuario_id = auth.uid())
);
create policy "Usuario cria mensagens" on public.mensagens_vsl for insert with check (
  exists (select 1 from public.sessoes_vsl s where s.id = sessao_id and s.usuario_id = auth.uid())
);
