CREATE TABLE IF NOT EXISTS sales_payment_webhook_events (
  id SERIAL PRIMARY KEY,
  tenant_id TEXT NOT NULL,
  payment_provider TEXT NOT NULL,
  provider_account_id TEXT,
  external_event_id TEXT,
  external_payment_id TEXT,
  event_type TEXT NOT NULL,
  event_status TEXT NOT NULL DEFAULT 'received',
  signature_status TEXT NOT NULL DEFAULT 'unchecked',
  raw_payload_hash TEXT NOT NULL,
  normalized_payload_json TEXT NOT NULL DEFAULT '{}',
  headers_json TEXT NOT NULL DEFAULT '{}',
  received_at TEXT NOT NULL,
  processed_at TEXT,
  error_message TEXT,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_sales_payment_webhook_events_received
  ON sales_payment_webhook_events(tenant_id, received_at);
CREATE INDEX IF NOT EXISTS idx_sales_payment_webhook_events_payment
  ON sales_payment_webhook_events(tenant_id, payment_provider, external_payment_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_sales_payment_webhook_events_external_event_unique
  ON sales_payment_webhook_events(tenant_id, payment_provider, external_event_id)
  WHERE external_event_id IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS idx_sales_payments_tenant_external_payment_unique
  ON sales_payments(tenant_id, payment_provider, external_payment_id)
  WHERE external_payment_id IS NOT NULL;
