package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"
)

type GetAiChatHistoryLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetAiChatHistoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAiChatHistoryLogic {
	return &GetAiChatHistoryLogic{ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx)}
}

func (l *GetAiChatHistoryLogic) GetAiChatHistory(in *plant.AiChatHistoryReq) (*plant.AiChatHistoryResp, error) {
	var histories []plantModel.AiChatHistory
	var total int64
	db := l.svcCtx.DB.Model(&plantModel.AiChatHistory{}).Where("user_id = ?", in.UserId)
	db.Count(&total)
	page, size := in.Current, in.PageSize
	if page < 1 {
		page = 1
	}
	if size < 1 || size > 50 {
		size = 20
	}
	db.Order("created_at desc").Offset(int((page - 1) * size)).Limit(int(size)).Find(&histories)
	list := make([]*plant.AiChatHistoryInfo, 0, len(histories))
	for _, h := range histories {
		list = append(list, &plant.AiChatHistoryInfo{
			Id: h.ID, UserId: h.UserID, Question: h.Question, Answer: h.Answer,
			CreatedAt: h.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}
	return &plant.AiChatHistoryResp{List: list, Total: total}, nil
}
