package plant

import (
	"sundynix-go/global"
	plantModel "sundynix-go/model/plant"
)

type AiChatHistoryService struct{}

// SaveHistory 保存一条问答记录
func (s *AiChatHistoryService) SaveHistory(userId, question, answer string) error {
	record := plantModel.AiChatHistory{
		UserId:   userId,
		Question: question,
		Answer:   answer,
	}
	return global.DB.Create(&record).Error
}

// GetHistoryList 获取用户问答历史（分页，最新在前）
func (s *AiChatHistoryService) GetHistoryList(userId string, current, pageSize int) ([]plantModel.AiChatHistory, int64, error) {
	var list []plantModel.AiChatHistory
	var total int64

	db := global.DB.Model(&plantModel.AiChatHistory{}).Where("user_id = ?", userId)
	db.Count(&total)

	if current <= 0 {
		current = 1
	}
	if pageSize <= 0 || pageSize > 50 {
		pageSize = 20
	}
	offset := (current - 1) * pageSize

	err := db.Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&list).Error
	return list, total, err
}

// DeleteHistory 删除单条记录
func (s *AiChatHistoryService) DeleteHistory(userId, id string) error {
	return global.DB.Where("id = ? AND user_id = ?", id, userId).Delete(&plantModel.AiChatHistory{}).Error
}

// ClearHistory 清空用户所有历史
func (s *AiChatHistoryService) ClearHistory(userId string) error {
	return global.DB.Where("user_id = ?", userId).Delete(&plantModel.AiChatHistory{}).Error
}

// GetTodayCount 获取用户今日问答数量
func (s *AiChatHistoryService) GetTodayCount(userId string) (int64, error) {
	var count int64
	err := global.DB.Model(&plantModel.AiChatHistory{}).
		Where("user_id = ? AND DATE(created_at) = CURDATE()", userId).
		Count(&count).Error
	return count, err
}
