-- ============================================================
-- AGG-UAE ERP — Migration 53 — Phase M7-p4-h8
--   Fix lead_hours unit-of-measure for bended Primer→Lam
-- ============================================================
--
-- Migration 48 seeded bended Primer→Lamination with lead_hours=24
-- intending the semantic "1 working day = next day", but the
-- scheduler helper `scheduler_add_lead_hours()` interprets
-- lead_hours as WORKING-SHIFT-HOURS (8h per shift):
--
--   $days = ceil($hours / 8.0);  // 24 / 8 = 3 working days
--
-- So lead_hours=24 advanced ready_for[Lam] by THREE working days
-- instead of the intended ONE. Symptom: bended glasses primed
-- on day N became Lam-eligible on day N+3 (skipping Sundays),
-- leaving Lamination under-utilized for 2 days after every
-- bended primer batch.
--
-- Diagnostic warnings from M7-p4-h6/h7 surfaced this directly:
--   LAM-POOL-SKIP 2026-05-27 JF3 g10 W: rem=10 ready=2026-05-29
--   LAM-POOL-SKIP 2026-05-27 JF3 g11 FDL: rem=10 ready=2026-05-30
--
-- 1003/26 W primer was May 26 → ready_for[Lam] should be May 27
-- (next working day), but landed at May 29 (+3 working days).
--
-- Fix: 8 hours = 1 working shift = next working day per the
-- helper's ceil(8/8)=1 working-day-advance semantic. Keeps the
-- physical intent (cure overnight, lam next day) without the
-- 2-day-loss bug.
--
-- Idempotent: only updates rows currently at 24h. Re-runs find
-- nothing to update and no-op.

UPDATE STAGE_TRANSITION_LEAD_TIME
   SET lead_hours = 8
 WHERE from_stage = 'Primer Printing'
   AND to_stage   = 'Lamination'
   AND lead_mode  = 'fixed_hours'
   AND is_bended_filter = 'bended'
   AND lead_hours = 24;

-- Audit query to verify post-migration state.
SELECT from_stage, to_stage, size_class, is_bended_filter, lead_hours
  FROM STAGE_TRANSITION_LEAD_TIME
 WHERE from_stage = 'Primer Printing'
   AND to_stage   = 'Lamination'
 ORDER BY size_class, is_bended_filter;
