package com.dora.mapper;

import com.dora.entity.PlazaWorkLike;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 广场作品点赞Mapper
 * 
 * @author 1818AI
 * @since 2025-10-26
 */
@Mapper
public interface PlazaWorkLikeMapper {

    /**
     * 插入点赞记录
     */
    @Insert("INSERT INTO plaza_work_like (work_id, user_id, create_time) " +
            "VALUES (#{workId}, #{userId}, NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(PlazaWorkLike plazaWorkLike);

    /**
     * 删除点赞记录
     */
    @Delete("DELETE FROM plaza_work_like WHERE work_id = #{workId} AND user_id = #{userId}")
    int deleteByWorkIdAndUserId(@Param("workId") Long workId, @Param("userId") Long userId);

    /**
     * 检查用户是否已点赞
     */
    @Select("SELECT COUNT(*) FROM plaza_work_like WHERE work_id = #{workId} AND user_id = #{userId}")
    int existsByWorkIdAndUserId(@Param("workId") Long workId, @Param("userId") Long userId);

    /**
     * 查询用户点赞的作品ID列表
     */
    @Select("SELECT work_id FROM plaza_work_like WHERE user_id = #{userId}")
    List<Long> findWorkIdsByUserId(@Param("userId") Long userId);

    /**
     * 批量检查用户是否点赞（用于列表查询优化）
     */
    @Select("<script>" +
            "SELECT work_id FROM plaza_work_like " +
            "WHERE user_id = #{userId} " +
            "AND work_id IN " +
            "<foreach collection='workIds' item='workId' open='(' separator=',' close=')'>" +
            "  #{workId}" +
            "</foreach>" +
            "</script>")
    List<Long> findLikedWorkIds(@Param("userId") Long userId, @Param("workIds") List<Long> workIds);

    /**
     * 统计作品的点赞数
     */
    @Select("SELECT COUNT(*) FROM plaza_work_like WHERE work_id = #{workId}")
    int countByWorkId(@Param("workId") Long workId);

    /**
     * 查询用户点赞的作品列表（分页）
     */
    @Select("SELECT pwl.work_id, pwl.create_time " +
            "FROM plaza_work_like pwl " +
            "WHERE pwl.user_id = #{userId} " +
            "ORDER BY pwl.create_time DESC " +
            "LIMIT #{offset}, #{size}")
    List<PlazaWorkLike> findUserLikes(
            @Param("userId") Long userId,
            @Param("offset") int offset,
            @Param("size") int size
    );

    /**
     * 统计用户点赞总数
     */
    @Select("SELECT COUNT(*) FROM plaza_work_like WHERE user_id = #{userId}")
    long countUserLikes(@Param("userId") Long userId);
}

