package dao

import (
	"time"

	"gorm.io/gorm"
)

// 贴子点赞表

type PostLike struct {
	PostId    uint64    `gorm:"index;not null;comment:'帖子'"`
	UserId    int32     `gorm:"index;not null;comment:'点赞者'"`
	CreatedAt time.Time `gorm:"type:datetime(0)"`
}

// 点赞。如果已经点过赞了，则忽略。
func PostLike_Like(data *PostLike) error {
	return s.db.Where("user_id = ? and post_id = ?", data.UserId, data.PostId).FirstOrCreate(data).Error
}

// 去掉点赞
func PostLike_UnLike(userId int32, postId uint64) error {
	return s.db.Where("user_id = ? and post_id = ?", userId, postId).Delete(&PostLike{}).Error
}

// 获取点赞数
func PostLike_Count(postId uint64) (int64, error) {
	count := int64(0)
	if err := s.db.Model(&PostLike{}).Where("post_id = ?", postId).Count(&count).Error; err != nil && err != gorm.ErrRecordNotFound {
		return 0, err
	}
	return count, nil
}

// 批量获取帖子点赞数
func PostLike_Count_Batch(postIds []uint64) (map[uint64]int64, error) {
	type search_result_item struct {
		PostId    uint64
		LikeCount int64
	}
	var result []*search_result_item
	if err := s.db.Model(&PostLike{}).Where("post_id in (?)", postIds).Select("post_id,count(*) as like_count").Group("post_id").Scan(&result).Error; err != nil {
		return nil, err
	}

	reply := make(map[uint64]int64)
	for _, item := range result {
		reply[item.PostId] = item.LikeCount
	}
	return reply, nil
}

// 当前用户有没有点赞
func PostLike_Exists(userId int32, postId uint64) (bool, error) {
	count := int64(0)
	if err := s.db.Model(&PostLike{}).Where("user_id = ? and post_id = ?", userId, postId).Count(&count).Error; err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	return count != int64(0), nil
}

// 批量查询用户有没有点赞
func PostLike_Exists_Batch(userId int32, postIds []uint64) (map[uint64]bool, error) {
	var result []uint64
	if err := s.db.Model(&PostLike{}).Where("user_id = ?", userId).Where("post_id in (?)", postIds).Select("post_id").Group("post_id").Scan(&result).Error; err != nil {
		return nil, err
	}

	reply := make(map[uint64]bool)
	for _, post_id := range result {
		reply[post_id] = true
	}
	return reply, nil
}
