-- RDX Energia - banco das avaliacoes
create table if not exists fichas (
  id              bigserial primary key,
  tipo            text        not null check (tipo in ('investidor','usina')),
  criado_em       timestamptz not null default now(),
  origem_ip       text,
  user_agent      text,

  nome            text,
  email           text,
  telefone        text,
  cidade          text,

  respostas       jsonb       not null,

  pontos          integer,
  base            integer,
  percentual      integer,
  faixa           text,
  blocos          jsonb,
  cortes          jsonb,
  alertas         jsonb,

  consentimento   boolean     not null default false,
  consent_texto   text,

  sync_status     text        not null default 'pendente'
                  check (sync_status in ('pendente','enviado','erro','ignorado')),
  sync_tentativas integer     not null default 0,
  sync_erro       text,
  sync_lead_id    text,
  sync_em         timestamptz,

  parecer         text,
  notas_internas  text
);

create index if not exists idx_fichas_tipo       on fichas (tipo, criado_em desc);
create index if not exists idx_fichas_sync       on fichas (sync_status) where sync_status in ('pendente','erro');
create index if not exists idx_fichas_percentual on fichas (percentual desc);
create index if not exists idx_fichas_email      on fichas (lower(email));

create table if not exists usuarios (
  id          bigserial primary key,
  email       text unique not null,
  senha_hash  text        not null,
  nome        text,
  papel       text        not null default 'consultor' check (papel in ('admin','consultor')),
  criado_em   timestamptz not null default now(),
  ultimo_acesso timestamptz
);
