/*
  # Create configuracoes table

  Per-company settings: email, WhatsApp, reminders, defaults.
*/

CREATE TABLE IF NOT EXISTS configuracoes (
  id bigserial PRIMARY KEY,
  empresa_id bigint NOT NULL UNIQUE REFERENCES empresas(id) ON DELETE CASCADE,
  email_remetente text,
  nome_remetente text,
  smtp_host text,
  smtp_port smallint DEFAULT 587,
  smtp_username text,
  smtp_password text,
  smtp_encryption text DEFAULT 'tls',
  whatsapp_phone_number_id text,
  whatsapp_access_token text,
  whatsapp_verify_token text,
  whatsapp_ativo boolean DEFAULT false,
  regras_lembretes jsonb,
  lembrete_7d boolean DEFAULT true,
  lembrete_3d boolean DEFAULT true,
  lembrete_vencimento boolean DEFAULT true,
  lembrete_1d_atraso boolean DEFAULT true,
  lembrete_3d_atraso boolean DEFAULT true,
  lembrete_7d_atraso boolean DEFAULT true,
  juros_percentual numeric(5,2) DEFAULT 1.00,
  multa_percentual numeric(5,2) DEFAULT 2.00,
  gateway_padrao text,
  chave_pix text,
  tipo_chave_pix text,
  instrucoes_boleto text,
  website text,
  instagram text,
  facebook text,
  created_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now()
);

ALTER TABLE configuracoes ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Empresa members can read own configuracoes"
  ON configuracoes FOR SELECT
  TO authenticated
  USING (empresa_id = (SELECT empresa_id FROM usuarios WHERE supabase_uuid = auth.uid()));

CREATE POLICY "Insert configuracoes"
  ON configuracoes FOR INSERT
  TO authenticated
  WITH CHECK (empresa_id = (SELECT empresa_id FROM usuarios WHERE supabase_uuid = auth.uid()));

CREATE POLICY "Update configuracoes"
  ON configuracoes FOR UPDATE
  TO authenticated
  USING (empresa_id = (SELECT empresa_id FROM usuarios WHERE supabase_uuid = auth.uid()));
