package com.zioinfo.kintex.work.stats;

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

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

/** 통계 매퍼 — worklog 집계. DataScope: mineOnly 이면 writer 한정. */
@Mapper
public interface StatsMapper {

    String FILTER = """
              <if test="mineOnly">AND writer_id = #{userId}</if>
              <if test="eventId != null and eventId != ''">AND event_id = #{eventId}</if>
              <if test="fromDate != null and fromDate != ''">AND work_date &gt;= CAST(#{fromDate} AS date)</if>
              <if test="toDate != null and toDate != ''">AND work_date &lt;= CAST(#{toDate} AS date)</if>
            """;

    @Select("<script>SELECT status AS name, count(*) AS count, COALESCE(SUM(hours),0) AS hours "
            + "FROM worklog <where>1=1 " + FILTER + "</where> GROUP BY status ORDER BY status</script>")
    List<Map<String, Object>> byStatus(Map<String, Object> q);

    @Select("<script>SELECT work_type AS name, count(*) AS count, COALESCE(SUM(hours),0) AS hours "
            + "FROM worklog <where>1=1 " + FILTER + "</where> GROUP BY work_type ORDER BY work_type</script>")
    List<Map<String, Object>> byType(Map<String, Object> q);

    @Select("<script>SELECT writer_name AS name, count(*) AS count, COALESCE(SUM(hours),0) AS hours "
            + "FROM worklog <where>1=1 " + FILTER + "</where> GROUP BY writer_id, writer_name "
            + "ORDER BY count DESC LIMIT 50</script>")
    List<Map<String, Object>> byWriter(Map<String, Object> q);

    @Select("<script>SELECT count(*) AS count, COALESCE(SUM(hours),0) AS hours "
            + "FROM worklog <where>1=1 " + FILTER + "</where></script>")
    Map<String, Object> summary(Map<String, Object> q);
}
