-- 024_CleanOrphanIdempotencyKeys.sql
-- Removes orphaned idempotency keys for invoices that were never successfully posted.
-- These occur when the process_transaction function fails AFTER inserting the idempotency key
-- but BEFORE creating ledger entries (e.g., due to missing period).

-- Only run if the processed_transactions table exists (it's in ledger schema)
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'processed_transactions') THEN
        DELETE FROM processed_transactions pt
        WHERE pt.idempotency_key LIKE 'invoice-send-%'
          AND NOT EXISTS (
            SELECT 1 FROM ledger_entries le
            WHERE le.idempotency_key = pt.idempotency_key
          );
    END IF;
END $$;
