package dao

import (
	"fmt"

	"github.com/tidbcloud/aipower/commons/database"
	"github.com/tidbcloud/aipower/commons/utils"
	"github.com/tidbcloud/aipower/internal/bean/dto"
	"github.com/tidbcloud/aipower/internal/bean/entity"

	"github.com/tidbcloud/tiinf/errs"
)

func CreateBotInteractRecord(record *entity.BotInteractRecord) (*entity.BotInteractRecord, error) {
	err := database.DBConn.DB.Table(entity.TableBotInteractRecord).Save(record).Error
	if err != nil {
		return nil, errs.WrapGORMError(err, fmt.Sprintf("insert BotInteractRecord failed: %+v", record))
	}
	return record, nil
}

func GetBotInteractRecordBySessionIDCreatedBy(sessionID, createdBy string) ([]*entity.BotInteractRecord, error) {
	var recs []*entity.BotInteractRecord
	err := database.DBConn.DB.Table(entity.TableBotInteractRecord).
		Where("session_id = ?", sessionID).
		Where("created_by = ?", createdBy).
		Find(&recs).Error
	return recs, err
}

func GetBotInteractRecordByCreatedByQuestionGECreatedAt(createdBy, question string, createdAt utils.JsonTime) ([]*entity.BotInteractRecord, error) {
	var recs []*entity.BotInteractRecord
	err := database.DBConn.DB.Table(entity.TableBotInteractRecord).
		Where("question = ?", question).
		Where("created_by = ?", createdBy).
		Where("created_at >= ?", createdAt).
		Order("id desc").
		Find(&recs).Error
	return recs, err
}

func ListBotInteractRecord(param *dto.ListInteractRecParam) (*dto.ListInteractRecResult, error) {
	tx := database.DBConn.DB.Table(entity.TableBotInteractRecord)
	if len(param.Filter.ID) > 0 {
		tx = tx.Where("id in (?)", param.Filter.ID)
	}
	if param.Filter.SessionID != "" {
		tx = tx.Where("session_id = ?", param.Filter.SessionID)
	}
	if param.Filter.Question != "" {
		tx = tx.Where("question like ?", "%"+param.Filter.Question+"%")
	}
	var sortBy = "id"
	if param.SortBy != "" {
		sortBy = param.SortBy
	}
	var order = "desc"
	if param.Order != "" {
		order = param.Order
	}
	tx = tx.Order(fmt.Sprintf("%s %s", sortBy, order))

	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return nil, err
	}

	if param.PageNo > 0 && param.PageSize > 0 {
		offset := (param.PageNo - 1) * param.PageSize
		tx = tx.Limit(param.PageSize).Offset(offset)
	}

	var recs []*entity.BotInteractRecord
	if err := tx.Find(&recs).Error; err != nil {
		return nil, err
	}

	result := &dto.ListInteractRecResult{
		Total: total,
		List:  recs,
	}

	return result, nil
}
