<?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.campus.activity.mapper.ActivityMapper">

    <select id="selectActivityPage" resultType="com.campus.activity.entity.Activity">
        SELECT a.*,
               (SELECT AVG(rating) FROM review r WHERE r.activity_id = a.id) as averageRating
        FROM activity a
        <where>
            a.deleted = 0
            <if test="status != null">
                AND a.status = #{status}
            </if>
            <if test="keyword != null and keyword != ''">
                AND (a.title LIKE CONCAT('%', #{keyword}, '%')
                OR a.description LIKE CONCAT('%', #{keyword}, '%'))
            </if>
            <if test="category != null and category != ''">
                AND a.category = #{category}
            </if>
            <if test="startDate != null">
                AND a.start_time >= #{startDate}
            </if>
            <if test="endDate != null">
                AND a.end_time &lt;= #{endDate}
            </if>
        </where>
        ORDER BY a.start_time DESC
    </select>

    <select id="selectCalendarActivities" resultType="com.campus.activity.entity.Activity">
        SELECT *
        FROM activity
        WHERE deleted = 0
          AND YEAR(start_time) = #{year}
          AND MONTH(start_time) = #{month}
        ORDER BY start_time ASC
    </select>

    <select id="selectConflictActivities" resultType="com.campus.activity.entity.Activity">
        SELECT *
        FROM activity
        WHERE deleted = 0
          AND id != #{excludeActivityId}
          AND status != 3
          AND (
              (start_time &lt;= #{endTime} AND end_time >= #{startTime})
              OR (start_time &lt;= #{startTime} AND end_time >= #{startTime})
              OR (start_time >= #{startTime} AND end_time &lt;= #{endTime})
          )
    </select>

</mapper>