/*
  # Create empresas table (standalone, no FK to usuarios)

  1. New Tables
    - `empresas` (tenants/companies)

  2. Security
    - Enable RLS on `empresas`
*/

CREATE TABLE IF NOT EXISTS empresas (
  id bigserial PRIMARY KEY,
  nome text NOT NULL,
  nome_fantasia text,
  cnpj text UNIQUE,
  email text NOT NULL UNIQUE,
  telefone text,
  subdominio text UNIQUE,
  dominio_customizado text UNIQUE,
  logo_path text,
  favicon_path text,
  cor_primaria text NOT NULL DEFAULT '#0d6efd',
  cor_secundaria text NOT NULL DEFAULT '#6c757d',
  status text NOT NULL DEFAULT 'pendente' CHECK (status IN ('pendente','ativo','bloqueado','cancelado','trial')),
  plano_id bigint REFERENCES planos(id) ON DELETE SET NULL,
  trial_ends_at timestamptz,
  responsavel_nome text,
  responsavel_email text,
  responsavel_telefone text,
  cep text,
  logradouro text,
  numero text,
  complemento text,
  bairro text,
  cidade text,
  estado text,
  observacoes text,
  aprovado_em timestamptz,
  aprovado_por bigint,
  bloqueado_em timestamptz,
  motivo_bloqueio text,
  created_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now(),
  deleted_at timestamptz
);

CREATE INDEX idx_empresas_status ON empresas(status);
CREATE INDEX idx_empresas_plano ON empresas(plano_id);

ALTER TABLE empresas ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Authenticated can read empresas"
  ON empresas FOR SELECT
  TO authenticated
  USING (true);

CREATE POLICY "Super admin can manage empresas"
  ON empresas FOR ALL
  TO authenticated
  USING (true)
  WITH CHECK (true);
