/*
  # Create gateways_pagamento table

  Per-company encrypted gateway credentials.
*/

CREATE TABLE IF NOT EXISTS gateways_pagamento (
  id bigserial PRIMARY KEY,
  empresa_id bigint NOT NULL REFERENCES empresas(id) ON DELETE CASCADE,
  provedor text NOT NULL CHECK (provedor IN ('mercado_pago','pagseguro')),
  nome text NOT NULL,
  ativo boolean NOT NULL DEFAULT false,
  ambiente text NOT NULL DEFAULT 'sandbox' CHECK (ambiente IN ('sandbox','producao')),
  credenciais jsonb,
  webhook_secret text,
  configuracoes jsonb,
  created_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now()
);

CREATE INDEX idx_gateways_empresa ON gateways_pagamento(empresa_id, ativo);

ALTER TABLE gateways_pagamento ENABLE ROW LEVEL SECURITY;

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

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

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

CREATE POLICY "Delete gateways"
  ON gateways_pagamento FOR DELETE
  TO authenticated
  USING (empresa_id = (SELECT empresa_id FROM usuarios WHERE supabase_uuid = auth.uid()));
