-- LOT Reject Records Query
-- Retrieves reject (defect) records for a LOT
--
-- Parameters:
--   container_id - CONTAINERID to query (16-char hex)
--
-- Note: Aligns output semantics and ordering with Reject History detail:
--       - REJECT_TOTAL_QTY = REJECT + STANDBY + QTYTOPROCESS + INPROCESS + PROCESSED
--       - DEFECT_QTY uses DEFECTQTY (non-charge-off scrap)
--       - Order: TXN_DAY desc, WORKCENTER sequence asc, WORKCENTER asc, REJECT_TOTAL_QTY desc, LOT asc

WITH spec_map AS (
    SELECT
        SPEC,
        MIN(WORK_CENTER) KEEP (
            DENSE_RANK FIRST ORDER BY WORKCENTERSEQUENCE_GROUP
        ) AS WORK_CENTER,
        MIN(WORK_CENTER_GROUP) KEEP (
            DENSE_RANK FIRST ORDER BY WORKCENTERSEQUENCE_GROUP
        ) AS WORKCENTER_GROUP,
        MIN(WORKCENTERSEQUENCE_GROUP) AS WORKCENTERSEQUENCE_GROUP
    FROM DWH.DW_MES_SPEC_WORKCENTER_V
    WHERE SPEC IS NOT NULL
    GROUP BY SPEC
)
SELECT
    r.CONTAINERID,
    NVL(TRIM(c.CONTAINERNAME), TRIM(r.CONTAINERID)) AS CONTAINERNAME,
    NVL(TRIM(sm.WORK_CENTER), NVL(TRIM(r.WORKCENTERNAME), '(NA)')) AS WORKCENTERNAME,
    NVL(TRIM(sm.WORKCENTER_GROUP), NVL(TRIM(r.WORKCENTERNAME), '(NA)')) AS WORKCENTER_GROUP,
    NVL(sm.WORKCENTERSEQUENCE_GROUP, 999) AS WORKCENTERSEQUENCE_GROUP,
    NVL(TRIM(c.PRODUCTLINENAME), '(NA)') AS PRODUCTLINENAME,
    NVL(TRIM(c.PJ_FUNCTION), '(NA)') AS PJ_FUNCTION,
    NVL(TRIM(c.PJ_TYPE), '(NA)') AS PJ_TYPE,
    NVL(TRIM(c.PRODUCTNAME), '(NA)') AS PRODUCTNAME,
    NVL(TRIM(r.SPECNAME), '(NA)') AS SPECNAME,
    NVL(TRIM(r.LOSSREASONNAME), '(未填寫)') AS LOSSREASONNAME,
    NVL(TRIM(r.EQUIPMENTNAME), '(NA)') AS EQUIPMENTNAME,
    TRIM(r.REJECTCOMMENT) AS REJECTCOMMENT,
    NVL(r.REJECTQTY, 0) AS REJECT_QTY,
    NVL(r.STANDBYQTY, 0) AS STANDBY_QTY,
    NVL(r.QTYTOPROCESS, 0) AS QTYTOPROCESS_QTY,
    NVL(r.INPROCESSQTY, 0) AS INPROCESS_QTY,
    NVL(r.PROCESSEDQTY, 0) AS PROCESSED_QTY,
    NVL(r.REJECTQTY, 0)
      + NVL(r.STANDBYQTY, 0)
      + NVL(r.QTYTOPROCESS, 0)
      + NVL(r.INPROCESSQTY, 0)
      + NVL(r.PROCESSEDQTY, 0) AS REJECT_TOTAL_QTY,
    NVL(r.DEFECTQTY, 0) AS DEFECT_QTY,
    r.TXNDATE AS TXN_TIME,
    r.TXNDATE,
    TRUNC(r.TXNDATE) AS TXN_DAY
FROM DWH.DW_MES_LOTREJECTHISTORY r
LEFT JOIN DWH.DW_MES_CONTAINER c
  ON c.CONTAINERID = r.CONTAINERID
LEFT JOIN spec_map sm
  ON sm.SPEC = TRIM(r.SPECNAME)
WHERE r.CONTAINERID = :container_id
ORDER BY
    TRUNC(r.TXNDATE) DESC,
    NVL(sm.WORKCENTERSEQUENCE_GROUP, 999) ASC,
    NVL(TRIM(sm.WORK_CENTER), NVL(TRIM(r.WORKCENTERNAME), '(NA)')) ASC,
    NVL(r.REJECTQTY, 0)
      + NVL(r.STANDBYQTY, 0)
      + NVL(r.QTYTOPROCESS, 0)
      + NVL(r.INPROCESSQTY, 0)
      + NVL(r.PROCESSEDQTY, 0) DESC,
    NVL(TRIM(c.CONTAINERNAME), TRIM(r.CONTAINERID)) ASC,
    r.TXNDATE DESC
