create unique index if not exists idx_tenant_invoices_usage_overage_auto_unique
  on public.tenant_invoices(tenant_id, billing_period_start, billing_period_end)
  where invoice_type = 'usage_overage'
    and status <> 'void'
    and metadata->>'source' = 'usage_overage_auto';

comment on index public.idx_tenant_invoices_usage_overage_auto_unique is
  'Prevents duplicate automatic SaaS usage-overage invoices for the same tenant and billing period while allowing voided invoices to be regenerated.';
