-- Rollback: balik ke rule lama (19 minggu = 133 hari)

BEGIN;

UPDATE laying_transfers lt
SET economic_cutoff_date = sub.cutoff_date,
    updated_at = NOW()
FROM (
    SELECT
        lt2.id AS transfer_id,
        (MIN(pc.chick_in_date)::date + INTERVAL '133 days')::date AS cutoff_date
    FROM laying_transfers lt2
    JOIN project_chickins pc ON pc.project_flock_kandang_id = lt2.source_project_flock_kandang_id
    WHERE lt2.deleted_at IS NULL
      AND lt2.source_project_flock_kandang_id IS NOT NULL
      AND pc.deleted_at IS NULL
    GROUP BY lt2.id
) sub
WHERE lt.id = sub.transfer_id
  AND lt.deleted_at IS NULL;

COMMIT;
