-- Existing Stripe invoices predate object watermarks. Force the first later
-- event to reconcile against Stripe instead of treating it as authoritative.
INSERT INTO provider_object_event_watermarks (
  provider, object_type, provider_object_id,
  last_event_created, last_event_rank, last_event_id,
  is_deleted, requires_reconciliation, reconciliation_reason,
  updated_at
)
SELECT
  'stripe', 'invoice', provider_invoice_id,
  0, 0, 'reconcile:migration:020',
  false, true, 'migration_020_existing_invoice',
  NOW()
FROM invoices
WHERE provider = 'stripe'
  AND provider_invoice_id IS NOT NULL
ON CONFLICT (provider, object_type, provider_object_id) DO NOTHING;

-- A non-paid invoice must never retain the timestamp from an older paid
-- payload. Clean historical contradictions before enforcing the invariant.
UPDATE invoices
SET paid_at = NULL
WHERE status <> 'paid'
  AND paid_at IS NOT NULL;

ALTER TABLE invoices
  ADD CONSTRAINT invoices_paid_at_status_check
  CHECK (paid_at IS NULL OR status = 'paid') NOT VALID;

ALTER TABLE invoices
  VALIDATE CONSTRAINT invoices_paid_at_status_check;
