-- Reject History Performance (Daily Grain, Per-LOT)
-- Like performance_daily.sql but keeps CONTAINERID in GROUP BY for per-LOT detail rows.
--
-- Parameters:
--   :start_date - Start date (YYYY-MM-DD)
--   :end_date   - End date (YYYY-MM-DD)

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
),
reject_raw AS (
    SELECT
        r.TXNDATE,
        TRUNC(r.TXNDATE) AS TXN_DAY,
        TO_CHAR(TRUNC(r.TXNDATE), 'YYYY-MM') AS TXN_MONTH,
        r.CONTAINERID,
        NVL(TRIM(c.CONTAINERNAME), TRIM(r.CONTAINERID)) AS CONTAINERNAME,
        NVL(TRIM(r.PJ_WORKORDER), TRIM(c.MFGORDERNAME)) AS PJ_WORKORDER,
        NVL(TRIM(c.PJ_TYPE), '(NA)') AS PJ_TYPE,
        NVL(TRIM(c.PJ_FUNCTION), '(NA)') AS PJ_FUNCTION,
        NVL(TRIM(c.PRODUCTNAME), '(NA)') AS PRODUCTNAME,
        NVL(TRIM(c.PRODUCTLINENAME), '(NA)') AS PRODUCTLINENAME,
        NVL(TRIM(c.OBJECTTYPE), '(NA)') AS SCRAP_OBJECTTYPE,
        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(r.SPECNAME), '(NA)') AS SPECNAME,
        NVL(TRIM(r.EQUIPMENTNAME), '(NA)') AS EQUIPMENTNAME,
        NVL(
            TRIM(REGEXP_SUBSTR(r.EQUIPMENTNAME, '[^,]+', 1, 1)),
            NVL(TRIM(r.EQUIPMENTNAME), '(NA)')
        ) AS PRIMARY_EQUIPMENTNAME,
        NVL(TRIM(r.LOSSREASONNAME), '(未填寫)') AS LOSSREASONNAME,
        NVL(
            TRIM(REGEXP_SUBSTR(NVL(TRIM(r.LOSSREASONNAME), '(未填寫)'), '^[^_[:space:]-]+')),
            NVL(TRIM(r.LOSSREASONNAME), '(未填寫)')
        ) AS LOSSREASON_CODE,
        NVL(TRIM(r.REJECTCATEGORYNAME), '(未填寫)') AS REJECTCATEGORYNAME,
        TRIM(r.REJECTCOMMENT) AS REJECTCOMMENT,
        NVL(r.MOVEINQTY, 0) AS MOVEINQTY,
        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,
        ROW_NUMBER() OVER (
            PARTITION BY NVL(
                TRIM(r.HISTORYMAINLINEID),
                TRIM(r.CONTAINERID) || ':' || TO_CHAR(r.TXNDATE, 'YYYYMMDDHH24MISS') || ':' || NVL(TRIM(r.SPECID), '-')
            )
            ORDER BY NVL(TRIM(r.LOSSREASONNAME), ' ')
        ) AS EVENT_RN
    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 {{ BASE_WHERE }}
),
daily_agg AS (
    SELECT
        TXN_DAY,
        TXN_MONTH,
        CONTAINERID,
        CONTAINERNAME,
        PJ_FUNCTION,
        PRODUCTNAME,
        WORKCENTER_GROUP,
        WORKCENTERSEQUENCE_GROUP,
        WORKCENTERNAME,
        SPECNAME,
        EQUIPMENTNAME,
        PRIMARY_EQUIPMENTNAME,
        PRODUCTLINENAME,
        SCRAP_OBJECTTYPE,
        PJ_TYPE,
        LOSSREASONNAME,
        LOSSREASON_CODE,
        REJECTCATEGORYNAME,
        MAX(REJECTCOMMENT) AS REJECTCOMMENT,
        MIN(TXNDATE) AS TXN_TIME,
        COUNT(*) AS REJECT_EVENT_ROWS,
        COUNT(DISTINCT PJ_WORKORDER) AS AFFECTED_WORKORDER_COUNT,
        SUM(CASE WHEN EVENT_RN = 1 THEN MOVEINQTY ELSE 0 END) AS MOVEIN_QTY,
        SUM(REJECT_QTY) AS REJECT_QTY,
        SUM(REJECT_TOTAL_QTY) AS REJECT_TOTAL_QTY,
        SUM(DEFECT_QTY) AS DEFECT_QTY,
        SUM(STANDBY_QTY) AS STANDBY_QTY,
        SUM(QTYTOPROCESS_QTY) AS QTYTOPROCESS_QTY,
        SUM(INPROCESS_QTY) AS INPROCESS_QTY,
        SUM(PROCESSED_QTY) AS PROCESSED_QTY
    FROM reject_raw
    GROUP BY
        TXN_DAY,
        TXN_MONTH,
        CONTAINERID,
        CONTAINERNAME,
        PJ_FUNCTION,
        PRODUCTNAME,
        WORKCENTER_GROUP,
        WORKCENTERSEQUENCE_GROUP,
        WORKCENTERNAME,
        SPECNAME,
        EQUIPMENTNAME,
        PRIMARY_EQUIPMENTNAME,
        PRODUCTLINENAME,
        SCRAP_OBJECTTYPE,
        PJ_TYPE,
        LOSSREASONNAME,
        LOSSREASON_CODE,
        REJECTCATEGORYNAME
)
SELECT
    TXN_TIME,
    TXN_DAY,
    TXN_MONTH,
    CONTAINERID,
    CONTAINERNAME,
    PJ_FUNCTION,
    PRODUCTNAME,
    WORKCENTER_GROUP,
    WORKCENTERSEQUENCE_GROUP,
    WORKCENTERNAME,
    SPECNAME,
    EQUIPMENTNAME,
    PRIMARY_EQUIPMENTNAME,
    PRODUCTLINENAME,
    SCRAP_OBJECTTYPE,
    PJ_TYPE,
    LOSSREASONNAME,
    LOSSREASON_CODE,
    REJECTCATEGORYNAME,
    REJECTCOMMENT,
    REJECT_EVENT_ROWS,
    AFFECTED_WORKORDER_COUNT,
    MOVEIN_QTY,
    REJECT_QTY,
    REJECT_TOTAL_QTY,
    DEFECT_QTY,
    STANDBY_QTY,
    QTYTOPROCESS_QTY,
    INPROCESS_QTY,
    PROCESSED_QTY,
    CASE
        WHEN MOVEIN_QTY = 0 THEN 0
        ELSE ROUND(REJECT_TOTAL_QTY * 100 / MOVEIN_QTY, 4)
    END AS REJECT_RATE_PCT,
    CASE
        WHEN MOVEIN_QTY = 0 THEN 0
        ELSE ROUND(DEFECT_QTY * 100 / MOVEIN_QTY, 4)
    END AS DEFECT_RATE_PCT,
    CASE
        WHEN (REJECT_TOTAL_QTY + DEFECT_QTY) = 0 THEN 0
        ELSE ROUND(REJECT_TOTAL_QTY * 100 / (REJECT_TOTAL_QTY + DEFECT_QTY), 4)
    END AS REJECT_SHARE_PCT
FROM daily_agg
