-- =========================================================
-- INTakes / Cadastros Recebidos - Supabase Local
-- =========================================================

-- 0) Extensões úteis (geralmente já existem no Supabase, mas é seguro)
create extension if not exists pgcrypto;

-- 1) Função padrão para updated_at
create or replace function public.set_updated_at()
returns trigger
language plpgsql
as $$
begin
  new.updated_at = now();
  return new;
end;
$$;

-- 2) Tabela patient_intake_requests (espelhando nuvem)
create table if not exists public.patient_intake_requests (
  id         uuid primary key default gen_random_uuid(),
  owner_id   uuid not null,
  token      text,
  name       text,
  email      text,
  phone      text,
  notes      text,
  consent    boolean not null default false,
  status     text not null default 'new',
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  payload    jsonb
);

-- 3) Índices (performance em listagem e filtros)
create index if not exists idx_intakes_owner_created
  on public.patient_intake_requests (owner_id, created_at desc);

create index if not exists idx_intakes_owner_status_created
  on public.patient_intake_requests (owner_id, status, created_at desc);

create index if not exists idx_intakes_status_created
  on public.patient_intake_requests (status, created_at desc);

-- 4) Trigger updated_at
drop trigger if exists trg_patient_intake_requests_updated_at on public.patient_intake_requests;

create trigger trg_patient_intake_requests_updated_at
before update on public.patient_intake_requests
for each row execute function public.set_updated_at();

-- 5) RLS
alter table public.patient_intake_requests enable row level security;

-- 6) Policies (iguais às que você mostrou na nuvem)
drop policy if exists intake_select_own on public.patient_intake_requests;
create policy intake_select_own
on public.patient_intake_requests
for select
to authenticated
using (owner_id = auth.uid());

drop policy if exists intake_update_own on public.patient_intake_requests;
create policy intake_update_own
on public.patient_intake_requests
for update
to authenticated
using (owner_id = auth.uid())
with check (owner_id = auth.uid());

drop policy if exists "delete own intake requests" on public.patient_intake_requests;
create policy "delete own intake requests"
on public.patient_intake_requests
for delete
to authenticated
using (owner_id = auth.uid());

-- =========================================================
-- OPCIONAL (RECOMENDADO): registrar conversão
-- =========================================================
-- Se você pretende marcar intake como convertido e guardar o patient_id:
alter table public.patient_intake_requests
  add column if not exists converted_patient_id uuid;

create index if not exists idx_intakes_converted_patient_id
  on public.patient_intake_requests (converted_patient_id);

-- Opcional: impedir delete de intakes convertidos (melhor para auditoria)
-- (Se quiser manter delete liberado como na nuvem, comente este bloco.)
drop policy if exists "delete own intake requests" on public.patient_intake_requests;
create policy "delete_own_intakes_not_converted"
on public.patient_intake_requests
for delete
to authenticated
using (owner_id = auth.uid() and status <> 'converted');

-- =========================================================
-- OPCIONAL: check de status (evita status inválido)
-- =========================================================
alter table public.patient_intake_requests
  drop constraint if exists chk_intakes_status;

alter table public.patient_intake_requests
  add constraint chk_intakes_status
  check (status in ('new', 'converted', 'rejected'));
