package com.dora.mapper;

import com.dora.entity.CourseLike;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 课程点赞Mapper接口
 */
@Mapper
public interface CourseLikeMapper {

    /**
     * 根据用户ID和课程ID查询点赞记录（包含已删除的）
     */
    @Select("SELECT * FROM course_like WHERE user_id = #{userId} AND course_id = #{courseId}")
    CourseLike selectByUserAndCourseIncludeDeleted(@Param("userId") Long userId, @Param("courseId") Long courseId);

    /**
     * 根据用户ID和课程ID查询有效的点赞记录
     */
    @Select("SELECT * FROM course_like WHERE user_id = #{userId} AND course_id = #{courseId} AND is_deleted = 0")
    CourseLike selectByUserAndCourse(@Param("userId") Long userId, @Param("courseId") Long courseId);

    /**
     * 插入点赞记录
     */
    @Insert("INSERT INTO course_like (user_id, course_id, create_time, is_deleted) VALUES (#{userId}, #{courseId}, NOW(), 0)")
    int insert(CourseLike courseLike);

    /**
     * 安全插入点赞记录（忽略重复）
     */
    @Insert("INSERT IGNORE INTO course_like (user_id, course_id, create_time, is_deleted) VALUES (#{userId}, #{courseId}, NOW(), 0)")
    int insertIgnore(CourseLike courseLike);

    /**
     * 逻辑删除点赞记录
     */
    @Update("UPDATE course_like SET is_deleted = 1 WHERE user_id = #{userId} AND course_id = #{courseId}")
    int deleteByUserAndCourse(@Param("userId") Long userId, @Param("courseId") Long courseId);

    /**
     * 恢复点赞记录（将已删除的记录标记为有效）
     */
    @Update("UPDATE course_like SET is_deleted = 0, create_time = NOW() WHERE user_id = #{userId} AND course_id = #{courseId}")
    int restoreByUserAndCourse(@Param("userId") Long userId, @Param("courseId") Long courseId);

    /**
     * 统计课程的点赞数量
     */
    @Select("SELECT COUNT(*) FROM course_like WHERE course_id = #{courseId} AND is_deleted = 0")
    int countByCourseId(@Param("courseId") Long courseId);

    /**
     * 获取用户点赞的课程列表（包含课程信息）
     */
    @Select("SELECT cl.id, cl.user_id, cl.course_id, cl.create_time, " +
            "c.title as course_title, c.description as course_description, " +
            "c.cover_url, c.price, c.is_free, c.level, c.category, " +
            "u.username as creator_username " +
            "FROM course_like cl " +
            "LEFT JOIN course c ON cl.course_id = c.id " +
            "LEFT JOIN user u ON c.user_id = u.id " +
            "WHERE cl.user_id = #{userId} AND cl.is_deleted = 0 AND c.is_deleted = 0 " +
            "ORDER BY cl.create_time DESC LIMIT #{offset}, #{size}")
    List<CourseLikeWithInfo> selectByUserIdWithCourseInfo(@Param("userId") Long userId, @Param("offset") int offset, @Param("size") int size);

    /**
     * 统计用户点赞的课程数量
     */
    @Select("SELECT COUNT(*) FROM course_like cl LEFT JOIN course c ON cl.course_id = c.id WHERE cl.user_id = #{userId} AND cl.is_deleted = 0 AND c.is_deleted = 0")
    int countByUserId(@Param("userId") Long userId);

    /**
     * 检查是否存在重复的点赞记录
     */
    @Select("SELECT COUNT(*) FROM course_like WHERE user_id = #{userId} AND course_id = #{courseId} AND is_deleted = 0")
    int countDuplicateLikes(@Param("userId") Long userId, @Param("courseId") Long courseId);

    /**
     * 删除重复的点赞记录（保留最早的一条）
     */
    @Update("DELETE cl1 FROM course_like cl1 " +
            "INNER JOIN course_like cl2 ON cl1.user_id = cl2.user_id AND cl1.course_id = cl2.course_id " +
            "WHERE cl1.user_id = #{userId} AND cl1.course_id = #{courseId} " +
            "AND cl1.is_deleted = 0 AND cl2.is_deleted = 0 " +
            "AND cl1.id > cl2.id")
    int deleteDuplicateLikes(@Param("userId") Long userId, @Param("courseId") Long courseId);

    /**
     * 课程点赞记录（包含课程信息）
     */
    class CourseLikeWithInfo {
        private Long id;
        private Long userId;
        private Long courseId;
        private String courseTitle;
        private String courseDescription;
        private String coverUrl;
        private java.math.BigDecimal price;
        private Integer isFree;
        private Integer level;
        private String category;
        private String creatorUsername;
        private java.time.LocalDateTime createTime;

        // Getters and Setters
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
        
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        
        public Long getCourseId() { return courseId; }
        public void setCourseId(Long courseId) { this.courseId = courseId; }
        
        public String getCourseTitle() { return courseTitle; }
        public void setCourseTitle(String courseTitle) { this.courseTitle = courseTitle; }
        
        public String getCourseDescription() { return courseDescription; }
        public void setCourseDescription(String courseDescription) { this.courseDescription = courseDescription; }
        
        public String getCoverUrl() { return coverUrl; }
        public void setCoverUrl(String coverUrl) { this.coverUrl = coverUrl; }
        
        public java.math.BigDecimal getPrice() { return price; }
        public void setPrice(java.math.BigDecimal price) { this.price = price; }
        
        public Integer getIsFree() { return isFree; }
        public void setIsFree(Integer isFree) { this.isFree = isFree; }
        
        public Integer getLevel() { return level; }
        public void setLevel(Integer level) { this.level = level; }
        
        public String getCategory() { return category; }
        public void setCategory(String category) { this.category = category; }
        
        public String getCreatorUsername() { return creatorUsername; }
        public void setCreatorUsername(String creatorUsername) { this.creatorUsername = creatorUsername; }
        
        public java.time.LocalDateTime getCreateTime() { return createTime; }
        public void setCreateTime(java.time.LocalDateTime createTime) { this.createTime = createTime; }
    }
}