package repository

import (
	"metazone.cc/metalab/internal/model"

	"gorm.io/gorm"
)

// NotificationRepo 消息/通知数据访问
type NotificationRepo struct {
	db *gorm.DB
}

// NewNotificationRepo 构造函数
func NewNotificationRepo(db *gorm.DB) *NotificationRepo {
	return &NotificationRepo{db: db}
}

// Create 创建消息
func (r *NotificationRepo) Create(n *model.Notification) error {
	return r.db.Create(n).Error
}

// ListByUser 分页查询用户消息
func (r *NotificationRepo) ListByUser(userID uint, offset, limit int) ([]model.Notification, error) {
	var list []model.Notification
	err := r.db.Where("user_id = ?", userID).
		Order("created_at DESC").
		Offset(offset).Limit(limit).
		Find(&list).Error
	return list, err
}

// CountByUser 统计用户消息总数
func (r *NotificationRepo) CountByUser(userID uint) (int64, error) {
	var count int64
	err := r.db.Model(&model.Notification{}).Where("user_id = ?", userID).Count(&count).Error
	return count, err
}

// CountUnread 统计用户未读消息数
func (r *NotificationRepo) CountUnread(userID uint) (int64, error) {
	var count int64
	err := r.db.Model(&model.Notification{}).
		Where("user_id = ? AND is_read = false", userID).
		Count(&count).Error
	return count, err
}

// MarkRead 标记单条消息为已读
func (r *NotificationRepo) MarkRead(id, userID uint) error {
	return r.db.Model(&model.Notification{}).
		Where("uid = ? AND user_id = ?", id, userID).
		Update("is_read", true).Error
}

// MarkAllRead 将用户所有未读消息标记为已读
func (r *NotificationRepo) MarkAllRead(userID uint) error {
	return r.db.Model(&model.Notification{}).
		Where("user_id = ? AND is_read = false", userID).
		Update("is_read", true).Error
}
