/*
 * Base facts query for hold_dataset_cache.
 * Fetches ALL hold/release records for the date range with all columns
 * needed to derive trend, reason pareto, duration, and detail list.
 *
 * Shift boundary: HOLDTXNDATE before 07:30 → same day, after 07:30 → next day.
 */
WITH history_base AS (
  SELECT
    CASE
      WHEN TO_CHAR(h.HOLDTXNDATE, 'HH24MI') >= '0730' THEN TRUNC(h.HOLDTXNDATE) + 1
      ELSE TRUNC(h.HOLDTXNDATE)
    END AS hold_day,
    CASE
      WHEN h.RELEASETXNDATE IS NULL THEN NULL
      WHEN TO_CHAR(h.RELEASETXNDATE, 'HH24MI') >= '0730' THEN TRUNC(h.RELEASETXNDATE) + 1
      ELSE TRUNC(h.RELEASETXNDATE)
    END AS release_day,
    h.CONTAINERID,
    NVL(TRIM(c.CONTAINERNAME), TRIM(h.CONTAINERID)) AS LOT_ID,
    h.PJ_WORKORDER,
    c.PRODUCTNAME,
    h.WORKCENTERNAME,
    h.HOLDREASONID,
    h.HOLDREASONNAME,
    NVL(h.QTY, 0) AS QTY,
    h.HOLDTXNDATE,
    h.HOLDEMP,
    h.HOLDCOMMENTS,
    h.RELEASETXNDATE,
    h.RELEASEEMP,
    h.RELEASECOMMENTS,
    h.NCRID,
    h.FUTUREHOLDCOMMENTS,
    CASE
      WHEN h.RELEASETXNDATE IS NULL THEN (SYSDATE - h.HOLDTXNDATE) * 24
      ELSE (h.RELEASETXNDATE - h.HOLDTXNDATE) * 24
    END AS HOLD_HOURS,
    CASE
      WHEN h.HOLDREASONNAME IN ({{ NON_QUALITY_REASONS }}) THEN 'non-quality'
      ELSE 'quality'
    END AS HOLD_TYPE,
    CASE
      WHEN h.FUTUREHOLDCOMMENTS IS NOT NULL THEN 1
      ELSE 0
    END AS IS_FUTURE_HOLD,
    ROW_NUMBER() OVER (
      PARTITION BY
        h.CONTAINERID,
        CASE
          WHEN TO_CHAR(h.HOLDTXNDATE, 'HH24MI') >= '0730' THEN TRUNC(h.HOLDTXNDATE) + 1
          ELSE TRUNC(h.HOLDTXNDATE)
        END
      ORDER BY h.HOLDTXNDATE DESC
    ) AS RN_HOLD_DAY,
    ROW_NUMBER() OVER (
      PARTITION BY h.CONTAINERID, h.HOLDREASONID
      ORDER BY h.HOLDTXNDATE
    ) AS RN_FUTURE_REASON
  FROM DWH.DW_MES_HOLDRELEASEHISTORY h
  LEFT JOIN DWH.DW_MES_CONTAINER c ON c.CONTAINERID = h.CONTAINERID
  WHERE (
      h.HOLDTXNDATE >= TO_DATE(:start_date || ' 073000', 'YYYY-MM-DD HH24MISS') - 1
      OR h.RELEASETXNDATE >= TO_DATE(:start_date || ' 073000', 'YYYY-MM-DD HH24MISS') - 1
      OR h.RELEASETXNDATE IS NULL
    )
    AND (
      h.HOLDTXNDATE <= TO_DATE(:end_date || ' 073000', 'YYYY-MM-DD HH24MISS')
      OR h.RELEASETXNDATE <= TO_DATE(:end_date || ' 073000', 'YYYY-MM-DD HH24MISS')
      OR h.RELEASETXNDATE IS NULL
    )
)
SELECT
  hold_day,
  release_day,
  CONTAINERID,
  LOT_ID,
  PJ_WORKORDER,
  PRODUCTNAME,
  WORKCENTERNAME,
  HOLDREASONID,
  HOLDREASONNAME,
  QTY,
  HOLDTXNDATE,
  HOLDEMP,
  HOLDCOMMENTS,
  RELEASETXNDATE,
  RELEASEEMP,
  RELEASECOMMENTS,
  NCRID,
  FUTUREHOLDCOMMENTS,
  HOLD_HOURS,
  HOLD_TYPE,
  IS_FUTURE_HOLD,
  RN_HOLD_DAY,
  RN_FUTURE_REASON,
  CASE
    WHEN IS_FUTURE_HOLD = 1 AND RN_FUTURE_REASON <> 1 THEN 0
    ELSE 1
  END AS FUTURE_HOLD_FLAG
FROM history_base
