<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="me.qwq.doghouse.dao.StatisticsMapper">

    <select id="getDatabaseVersion" resultType="java.lang.String">
        SELECT sqlite_version()
    </select>
    
    <select id="getPostAndCommentCountsWithDates" resultType="java.util.Map">
     WITH RECURSIVE numbers(n) AS (
            SELECT 0
            UNION ALL
            SELECT n + 1 FROM numbers WHERE n &lt; #{passDays} - 1
        ),
        days AS (
            SELECT
                DATE('now', '-' || n || ' day') AS generatedDate
            FROM numbers
        ),
        post_data AS (
            SELECT
                DATE(create_time) AS postDate,
                COUNT(post_id) AS postCount
            FROM post
            WHERE
                DATE(create_time) >= DATE('now', '-' || #{passDays} || ' day')
                AND post_status = 0
                AND is_deleted = 0
                <if test="postType != null">
                AND type = #{postType}
                </if>
            GROUP BY DATE(create_time)
        ),
        comment_data AS (
            SELECT
                DATE(create_time) AS commentDate,
                COUNT(id) AS commentCount
            FROM comment
            WHERE
                DATE(create_time) >= DATE('now', '-' || #{passDays} || ' day')
                AND comment_status = 0
                AND is_deleted = 0
            GROUP BY DATE(create_time)
        ),
        merged AS (
            SELECT
                d.generatedDate,
                COALESCE(p.postCount, 0) AS postCount,
                COALESCE(c.commentCount, 0) AS commentCount
            FROM days d
            LEFT JOIN post_data p ON p.postDate = d.generatedDate
            LEFT JOIN comment_data c ON c.commentDate = d.generatedDate
        ),
        sorted AS (
            SELECT * FROM merged ORDER BY generatedDate ASC
        )
        SELECT
            GROUP_CONCAT(generatedDate) AS dates,
            GROUP_CONCAT(postCount) AS postCounts,
            GROUP_CONCAT(commentCount) AS commentCounts
        FROM sorted;
    </select>

    
</mapper>
