-- 039: Add defer_until + idempotency markers to canada_crtc_orders
--
-- defer_until: timestamp until which the worker should not run this order's pipeline.
-- Used by the standard-vs-expedited delay system.
--
-- binder_emailed_at / binder_compiled_at / binder_uploaded_at: idempotency markers
-- for Steps 7-9 so the pipeline can resume after a defer without re-doing work
-- (preventing duplicate client emails).

ALTER TABLE canada_crtc_orders
    ADD COLUMN IF NOT EXISTS defer_until        TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS automation_note    TEXT,
    ADD COLUMN IF NOT EXISTS binder_compiled_at TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS binder_uploaded_at TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS binder_emailed_at  TIMESTAMPTZ;

-- Index for the deferred order poller
CREATE INDEX IF NOT EXISTS idx_crtc_orders_deferred
    ON canada_crtc_orders (defer_until)
    WHERE automation_status = 'Deferred' AND defer_until IS NOT NULL;
