-- GetActiveAlarms: Returns all currently active (uncleared) alarms
-- Uses: idx_alarm_events_active, idx_alarm_events_clear, idx_alarm_event_data_lookup
-- Expected performance: <200ms on 37K rows, <500ms on 1M+ rows
-- Param: :priorityList (comma-separated priority numbers, or empty string for all)

SELECT
  ae.id AS ID,
  ae.eventtime AS StartTimestamp,
  TIME_FORMAT(SEC_TO_TIME(TIMESTAMPDIFF(SECOND, ae.eventtime, NOW())), '%H:%i:%s') AS Duration,
  CONCAT(REPLACE(ae.displaypath, '_', '-'), ' ', SUBSTRING_INDEX(ae.source, ':/alm:', -1)) AS Description,
  CASE ae.priority
    WHEN 0 THEN 'Diagnostic' 
    WHEN 1 THEN 'Low' 
    WHEN 2 THEN 'Medium'
    WHEN 3 THEN 'High' 
    WHEN 4 THEN 'Critical' 
    ELSE 'Unknown'
  END AS Priority,
  CONCAT(ae.displaypath, '.HMI.Alarm.', SUBSTRING_INDEX(IFNULL(aed.strValue, ''), '/', -1)) AS Tag,
  SUBSTRING_INDEX(SUBSTRING_INDEX(IFNULL(aed.strValue, ''), '/', 2), '/', -1) AS Location,
  aed.strValue AS FullTag,
  ae.displaypath AS Device
FROM alarm_events ae FORCE INDEX (idx_alarm_events_active)
LEFT JOIN alarm_event_data aed FORCE INDEX (idx_alarm_event_data_lookup)
  ON aed.id = ae.id AND aed.propname = 'myTag'
WHERE ae.eventtype = 0
  AND ae.displaypath NOT LIKE '%System Startup%'
  AND ae.source NOT LIKE '%System Startup%'
  AND (:priorityList = '' OR FIND_IN_SET(CAST(ae.priority AS CHAR), :priorityList) > 0)
  -- FORCE INDEX ensures idx_alarm_events_clear is used in subquery
  AND NOT EXISTS (
    SELECT 1 
    FROM alarm_events clr FORCE INDEX (idx_alarm_events_clear)
    WHERE clr.eventid = ae.eventid 
      AND clr.eventtype = 1
  )
ORDER BY ae.eventtime DESC;