<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zioinfo.signage.mapper.DashboardMapper">

  <select id="getSummary" resultType="com.zioinfo.signage.domain.DashboardVo">
    SELECT
      (SELECT COUNT(*) FROM signage_store
       WHERE 1=1 <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS total_stores,
      (SELECT COUNT(*) FROM signage_store WHERE is_active = true
       <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS active_stores,
      (SELECT COUNT(*) FROM signage_alarm
       WHERE 1=1 <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS total_alarms,
      (SELECT COUNT(*) FROM signage_alarm WHERE status != 'RESOLVED'
       <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS unresolved_alarms,
      (SELECT COUNT(*) FROM signage_alarm WHERE severity = 'CRITICAL' AND status != 'RESOLVED'
       <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS critical_alarms,
      (SELECT COUNT(*) FROM signage_gateway
       WHERE 1=1 <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS total_devices,
      (SELECT COUNT(*) FROM signage_gateway WHERE status = 'ONLINE'
       <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS online_devices,
      (SELECT COUNT(*) FROM signage_gateway WHERE status = 'OFFLINE'
       <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS offline_devices,
      (SELECT COUNT(*) FROM signage_work_history WHERE created_at::date = CURRENT_DATE
       <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS total_work_today,
      (SELECT COUNT(*) FROM signage_work_history WHERE status = 'COMPLETED' AND completed_at::date = CURRENT_DATE
       <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS completed_work_today,
      (SELECT COUNT(*) FROM signage_pos_cvt WHERE status = 'PENDING'
       <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS pending_pos_cvt,
      (SELECT COUNT(*) FROM signage_pos_cvt WHERE status = 'PROCESSED' AND processed_at::date = CURRENT_DATE
       <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      ) AS processed_pos_cvt_today
  </select>

</mapper>
