<?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.unilife.mapper.CommentMapper">
    <resultMap id="commentResultMap" type="com.unilife.model.entity.Comment">
        <id column="id" property="id"/>
        <result column="post_id" property="postId"/>
        <result column="user_id" property="userId"/>
        <result column="content" property="content"/>
        <result column="parent_id" property="parentId"/>
        <result column="like_count" property="likeCount"/>
        <result column="status" property="status"/>
        <result column="created_at" property="createdAt"/>
        <result column="updated_at" property="updatedAt"/>
    </resultMap>
    
    <insert id="insert" parameterType="com.unilife.model.entity.Comment" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO comments (
            post_id, user_id, content, parent_id, like_count, status, created_at, updated_at
        ) VALUES (
            #{postId}, #{userId}, #{content}, #{parentId}, #{likeCount}, #{status}, NOW(), NOW()
        )
    </insert>
    
    <select id="getById" resultMap="commentResultMap">
        SELECT id, post_id, user_id, content, parent_id, like_count, status, created_at, updated_at
        FROM comments
        WHERE id = #{id} AND status != 0
    </select>
    
    <select id="getTopLevelCommentsByPostId" resultMap="commentResultMap">
        SELECT id, post_id, user_id, content, parent_id, like_count, status, created_at, updated_at
        FROM comments
        WHERE post_id = #{postId} AND parent_id IS NULL AND status != 0
        ORDER BY created_at DESC
    </select>
    
    <select id="getRepliesByParentId" resultMap="commentResultMap">
        SELECT id, post_id, user_id, content, parent_id, like_count, status, created_at, updated_at
        FROM comments
        WHERE parent_id = #{parentId} AND status != 0
        ORDER BY created_at ASC
    </select>
    
    <select id="getCountByPostId" resultType="java.lang.Integer">
        SELECT COUNT(*)
        FROM comments
        WHERE post_id = #{postId} AND status != 0
    </select>
    
    <update id="update" parameterType="com.unilife.model.entity.Comment">
        UPDATE comments
        SET content = #{content},
            updated_at = NOW()
        WHERE id = #{id}
    </update>
    
    <update id="delete">
        UPDATE comments
        SET status = 0,
            updated_at = NOW()
        WHERE id = #{id}
    </update>
    
    <update id="incrementLikeCount">
        UPDATE comments
        SET like_count = like_count + 1
        WHERE id = #{id}
    </update>
    
    <update id="decrementLikeCount">
        UPDATE comments
        SET like_count = GREATEST(like_count - 1, 0)
        WHERE id = #{id}
    </update>
</mapper>