-- Equipment Status Hours Query
-- Aggregates status hours by equipment for a time period
--
-- Parameters:
--   :start_date - Start date (YYYY-MM-DD)
--   :end_date - End date (YYYY-MM-DD)
--
-- Dynamic placeholders:
--   EQUIPMENT_FILTER - Equipment filter condition
--
-- Note: RESOURCESTATUS_SHIFT requires JOIN with RESOURCE to get RESOURCENAME
--       Uses HISTORYID = RESOURCEID relationship
--       Uses OLDSTATUSNAME/NEWSTATUSNAME (NOT STATUSNAME)
--       Uses TXNDATE (NOT SHIFTDATE)
--       Hours field: HOURS

SELECT
    r.RESOURCEID,
    r.RESOURCENAME,
    SUM(CASE WHEN s.NEWSTATUSNAME = 'PRD' THEN s.HOURS ELSE 0 END) AS PRD_HOURS,
    SUM(CASE WHEN s.NEWSTATUSNAME = 'SBY' THEN s.HOURS ELSE 0 END) AS SBY_HOURS,
    SUM(CASE WHEN s.NEWSTATUSNAME = 'UDT' THEN s.HOURS ELSE 0 END) AS UDT_HOURS,
    SUM(CASE WHEN s.NEWSTATUSNAME = 'SDT' THEN s.HOURS ELSE 0 END) AS SDT_HOURS,
    SUM(CASE WHEN s.NEWSTATUSNAME = 'EGT' THEN s.HOURS ELSE 0 END) AS EGT_HOURS,
    SUM(CASE WHEN s.NEWSTATUSNAME = 'NST' THEN s.HOURS ELSE 0 END) AS NST_HOURS,
    SUM(s.HOURS) AS TOTAL_HOURS,
    ROUND(
        SUM(CASE WHEN s.NEWSTATUSNAME = 'PRD' THEN s.HOURS ELSE 0 END) * 100.0 /
        NULLIF(
            SUM(CASE WHEN s.NEWSTATUSNAME IN ('PRD', 'SBY', 'UDT') THEN s.HOURS ELSE 0 END),
            0
        ),
        2
    ) AS OU_PERCENT
FROM DWH.DW_MES_RESOURCESTATUS_SHIFT s
JOIN DWH.DW_MES_RESOURCE r ON s.HISTORYID = r.RESOURCEID
WHERE s.TXNDATE >= TO_DATE(:start_date, 'YYYY-MM-DD')
  AND s.TXNDATE < TO_DATE(:end_date, 'YYYY-MM-DD') + 1
  AND {{ EQUIPMENT_FILTER }}
GROUP BY r.RESOURCEID, r.RESOURCENAME
ORDER BY r.RESOURCENAME
