-- Projeto de esquema PostgreSQL; NÃO aplicado a nenhum banco.
-- Autenticação real, autorização por API, criptografia de dados sensíveis e migração
-- devem ser implementadas e testadas antes do uso em produção.
CREATE TABLE IF NOT EXISTS app_users (
  id uuid PRIMARY KEY, login text UNIQUE NOT NULL, password_hash text NOT NULL,
  role text NOT NULL CHECK(role IN ('gestor','vendedor')),
  active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS representatives (
  id uuid PRIMARY KEY, company_name text NOT NULL, cnpj text UNIQUE,
  contact text, phone text, whatsapp text, core_number text,
  core_due date, core_status_manual text, contract_status text,
  status text NOT NULL DEFAULT 'Ativo',
  registration jsonb NOT NULL DEFAULT '{}'::jsonb,
  linked_user_id uuid UNIQUE REFERENCES app_users(id),
  created_at timestamptz NOT NULL DEFAULT now(),updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS representative_history (
  id uuid PRIMARY KEY, representative_id uuid NOT NULL REFERENCES representatives(id),
  category text, description text, status text, occurred_on date,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS representative_leads (
  id uuid PRIMARY KEY, representative_id uuid REFERENCES representatives(id),
  name text, stage text, refusal_reason text, details jsonb NOT NULL DEFAULT '{}'::jsonb
);
CREATE TABLE IF NOT EXISTS representative_tasks (
  id uuid PRIMARY KEY, representative_id uuid NOT NULL REFERENCES representatives(id),
  title text NOT NULL, due_on date, done boolean NOT NULL DEFAULT false
);
-- Política obrigatória na API: todas as rotas /management/representatives/*
-- exigem sessão autenticada com role='gestor'; não confiar no papel enviado pelo cliente.
