package impl

import (
	"ai_scheduler/internal/data/model"
	"ai_scheduler/tmpl/dataTemp"
	"ai_scheduler/utils"
	"context"
	"time"

	"github.com/gofiber/fiber/v2/log"
	"gorm.io/gorm"
)

type ChatHisImpl struct {
	dataTemp.DataTemp
	BaseRepository[model.AiChatHi]
	chatChannel chan model.AiChatHi
}

func NewChatHisImpl(db *utils.Db) *ChatHisImpl {
	return &ChatHisImpl{
		DataTemp:       *dataTemp.NewDataTemp(db, new(model.AiChatHi)),
		BaseRepository: NewBaseModel[model.AiChatHi](db.Client),
		chatChannel:    make(chan model.AiChatHi, 100),
	}
}

// WithSessionId 条件：会话ID
func (impl *ChatHisImpl) WithSessionId(sessionId interface{}) CondFunc {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("session_id = ?", sessionId)
	}
}

// 异步添加会话历史
func (impl *ChatHisImpl) AsyncCreate(ctx context.Context, chat model.AiChatHi) {
	impl.chatChannel <- chat
}

// 异步处理会话历史
func (impl *ChatHisImpl) AsyncProcess(ctx context.Context) {
	for {
		select {
		case chat := <-impl.chatChannel:
			log.Infof("ChatHistoryAsyncProcess chat: %v", chat)
			if err := impl.Create(&chat); err != nil {
				log.Errorf("ChatHistoryAsyncProcess err: %v", err)
			}
		case <-ctx.Done():
			log.Infof("ChatHistoryAsyncProcess ctx done")
			return
			// 定时打印通道大小
		case <-time.After(time.Second * 5):
			//log.Infof("ChatHistoryAsyncProcess channel len: %d", len(impl.chatChannel))
		}
	}
}

// his_id 条件：历史ID
func (impl *ChatHisImpl) WithHisId(hisId interface{}) CondFunc {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("his_id = ?", hisId)
	}
}
