-- Reject History Detail List (Paginated, Per-LOT)
-- Template slots:
--   BASE_WITH_CTE (lot-level base SQL via performance_daily_lot)
--   WHERE_CLAUSE (QueryBuilder-generated WHERE clause against alias b)

{{ BASE_WITH_CTE }},
filtered AS (
    SELECT
        b.*,
        COUNT(*) OVER () AS TOTAL_COUNT
    FROM base b
    {{ WHERE_CLAUSE }}
),
paged AS (
    SELECT *
    FROM filtered
    ORDER BY
        TXN_DAY DESC,
        WORKCENTERSEQUENCE_GROUP ASC,
        WORKCENTERNAME ASC,
        REJECT_TOTAL_QTY DESC,
        CONTAINERNAME ASC
    OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY
)
SELECT
    p.TXN_TIME,
    p.TXN_DAY,
    p.TXN_MONTH,
    p.WORKCENTER_GROUP,
    p.WORKCENTERSEQUENCE_GROUP,
    p.WORKCENTERNAME,
    p.SPECNAME,
    p.EQUIPMENTNAME,
    p.PRIMARY_EQUIPMENTNAME,
    p.PRODUCTLINENAME,
    p.PJ_TYPE,
    p.CONTAINERNAME,
    p.PJ_FUNCTION,
    p.PRODUCTNAME,
    p.LOSSREASONNAME,
    p.LOSSREASON_CODE,
    p.REJECTCOMMENT,
    p.REJECT_EVENT_ROWS,
    p.AFFECTED_WORKORDER_COUNT,
    p.MOVEIN_QTY,
    p.REJECT_QTY,
    p.REJECT_TOTAL_QTY,
    p.DEFECT_QTY,
    p.STANDBY_QTY,
    p.QTYTOPROCESS_QTY,
    p.INPROCESS_QTY,
    p.PROCESSED_QTY,
    p.REJECT_RATE_PCT,
    p.DEFECT_RATE_PCT,
    p.REJECT_SHARE_PCT,
    p.TOTAL_COUNT
FROM paged p
ORDER BY
    p.TXN_DAY DESC,
    p.WORKCENTERSEQUENCE_GROUP ASC,
    p.WORKCENTERNAME ASC,
    p.REJECT_TOTAL_QTY DESC,
    p.CONTAINERNAME ASC
