-- Migration: link legacy mt_bp_caf rows (caf_id IS NULL) to their earliest CAF cycle.
-- Run ONCE before deploying the multi-CAF feature.
-- Safe to re-run — WHERE caf_id IS NULL means already-linked rows are untouched.
-- Rollback: UPDATE mt_bp_caf SET caf_id = NULL WHERE <your condition>;

UPDATE mt_bp_caf
SET caf_id = (
    SELECT id
    FROM caf_master
    WHERE caf_master.bp_id = mt_bp_caf.bp_id
    ORDER BY cycle_no ASC
    LIMIT 1
)
WHERE caf_id IS NULL;
