-- Resource Distinct Statuses Query
-- Returns distinct status names from recent resource status changes
--
-- Parameters:
--   :days_back - Number of days to look back for status changes

WITH latest_txn AS (
    SELECT MAX(COALESCE(TXNDATE, LASTSTATUSCHANGEDATE)) AS MAX_TXNDATE
    FROM DWH.DW_MES_RESOURCESTATUS
)
SELECT DISTINCT s.NEWSTATUSNAME
FROM DWH.DW_MES_RESOURCE r
JOIN DWH.DW_MES_RESOURCESTATUS s ON r.RESOURCEID = s.HISTORYID
CROSS JOIN latest_txn lt
WHERE ((r.OBJECTCATEGORY = 'ASSEMBLY' AND r.OBJECTTYPE = 'ASSEMBLY')
    OR (r.OBJECTCATEGORY = 'WAFERSORT' AND r.OBJECTTYPE = 'WAFERSORT'))
  AND COALESCE(s.TXNDATE, s.LASTSTATUSCHANGEDATE) >= lt.MAX_TXNDATE - :days_back
  AND s.NEWSTATUSNAME IS NOT NULL
ORDER BY s.NEWSTATUSNAME
