-- WIP Summary Query
-- Returns overall WIP KPI statistics
--
-- WIP Status Logic:
--   RUN: EQUIPMENTCOUNT > 0
--   HOLD: EQUIPMENTCOUNT = 0 AND CURRENTHOLDCOUNT > 0
--   QUEUE: EQUIPMENTCOUNT = 0 AND CURRENTHOLDCOUNT = 0
--
-- Hold Type Logic:
--   Quality Hold: Not in NON_QUALITY_HOLD_REASONS
--   Non-Quality Hold: In NON_QUALITY_HOLD_REASONS
--
-- Dynamic placeholders:
--   WHERE_CLAUSE - Filter conditions
--   NON_QUALITY_REASONS - List of non-quality hold reason values

SELECT
    COUNT(*) as TOTAL_LOTS,
    SUM(QTY) as TOTAL_QTY_PCS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) > 0 THEN 1 ELSE 0 END) as RUN_LOTS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) > 0 THEN QTY ELSE 0 END) as RUN_QTY_PCS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) = 0
              AND COALESCE(CURRENTHOLDCOUNT, 0) > 0 THEN 1 ELSE 0 END) as HOLD_LOTS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) = 0
              AND COALESCE(CURRENTHOLDCOUNT, 0) > 0 THEN QTY ELSE 0 END) as HOLD_QTY_PCS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) = 0
              AND COALESCE(CURRENTHOLDCOUNT, 0) > 0
              AND (HOLDREASONNAME IS NULL OR HOLDREASONNAME NOT IN ({{ NON_QUALITY_REASONS }}))
              THEN 1 ELSE 0 END) as QUALITY_HOLD_LOTS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) = 0
              AND COALESCE(CURRENTHOLDCOUNT, 0) > 0
              AND (HOLDREASONNAME IS NULL OR HOLDREASONNAME NOT IN ({{ NON_QUALITY_REASONS }}))
              THEN QTY ELSE 0 END) as QUALITY_HOLD_QTY_PCS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) = 0
              AND COALESCE(CURRENTHOLDCOUNT, 0) > 0
              AND HOLDREASONNAME IN ({{ NON_QUALITY_REASONS }})
              THEN 1 ELSE 0 END) as NON_QUALITY_HOLD_LOTS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) = 0
              AND COALESCE(CURRENTHOLDCOUNT, 0) > 0
              AND HOLDREASONNAME IN ({{ NON_QUALITY_REASONS }})
              THEN QTY ELSE 0 END) as NON_QUALITY_HOLD_QTY_PCS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) = 0
              AND COALESCE(CURRENTHOLDCOUNT, 0) = 0 THEN 1 ELSE 0 END) as QUEUE_LOTS,
    SUM(CASE WHEN COALESCE(EQUIPMENTCOUNT, 0) = 0
              AND COALESCE(CURRENTHOLDCOUNT, 0) = 0 THEN QTY ELSE 0 END) as QUEUE_QTY_PCS,
    MAX(SYS_DATE) as DATA_UPDATE_DATE
FROM DWH.DW_MES_LOT_V
{{ WHERE_CLAUSE }}
