package com.zioinfo.kintex.admin;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * 관리자 대시보드 집계 매퍼 — event·hall_assignment·app_user·company read-only.
 * 진행 여부는 오늘 날짜(start≤오늘≤end) 기준. 마이그레이션 불변.
 *
 * <p>★멀티테넌시 2단계: 전역 KPI·라이브 행사는 tenant_id(event/app_user) 선행 필터로 격리(§1A-2 · §8-2).
 * {@code company}는 tenant_id 컬럼이 없어(1단계 범위 유지·신규 컬럼 금지) 킨텍스 등록업체 공용 레지스트리로
 * 스코프 제외 — 등록업체 수는 테넌트 무관 집계(설계 노트 기록).
 */
@Mapper
public interface AdminDashboardMapper {

    /** KPI 원자 집계 — 진행 행사·사용 홀·활성 사용자(테넌트 스코프)·등록업체 수(공용). */
    @Select("""
            SELECT
              (SELECT count(*) FROM event
                 WHERE tenant_id = #{tenantId}
                   AND start_date <= CURRENT_DATE AND end_date >= CURRENT_DATE) AS "ongoingEvents",
              (SELECT count(DISTINCT ha.hall_id) FROM hall_assignment ha JOIN event e ON e.id = ha.event_id
                 WHERE e.tenant_id = #{tenantId}
                   AND e.start_date <= CURRENT_DATE AND e.end_date >= CURRENT_DATE) AS "hallsInUse",
              (SELECT count(*) FROM app_user
                 WHERE tenant_id = #{tenantId} AND status = 'ACTIVE') AS "activeUsers",
              (SELECT count(*) FROM company) AS companies,
              (SELECT count(*) FROM event
                 WHERE tenant_id = #{tenantId} AND start_date > CURRENT_DATE) AS "upcomingEvents"
            """)
    Map<String, Object> findKpiCounts(@Param("tenantId") String tenantId);

    /** 진행 중(라이브) 행사 — 대표 홀·부스 수·홀 수용량. 테넌트 스코프. 최대 20건. */
    @Select("""
            SELECT e.id AS "eventId",
                   e.name,
                   COALESCE(h.label, '') AS hall,
                   e.status,
                   (SELECT count(*) FROM booth b JOIN layout l ON l.id = b.layout_id
                      WHERE l.event_id = e.id) AS "boothCount",
                   COALESCE((SELECT sum(h2.booth_capacity) FROM hall_assignment ha2
                      JOIN hall h2 ON h2.id = ha2.hall_id WHERE ha2.event_id = e.id), 0) AS capacity
            FROM event e
            LEFT JOIN LATERAL (
                SELECT hall_id FROM hall_assignment ha
                WHERE ha.event_id = e.id ORDER BY is_primary DESC LIMIT 1
            ) pa ON true
            LEFT JOIN hall h ON h.id = pa.hall_id
            WHERE e.tenant_id = #{tenantId}
              AND e.start_date <= CURRENT_DATE AND e.end_date >= CURRENT_DATE
            ORDER BY e.start_date DESC
            LIMIT 20
            """)
    List<Map<String, Object>> findLiveEvents(@Param("tenantId") String tenantId);
}
