package ai

import (
	"errors"
	"strings"

	"gorm.io/gorm"
	"senlinai-agent/backend/internal/models"
)

// ExpertFilter 是本地专家库的查询条件。
type ExpertFilter struct {
	Category string
	Query    string
}

func (s *SessionService) ListExperts(filter ExpertFilter) ([]models.SaAIExpertItem, error) {
	query := models.DBService.Model(&models.SaAIExpertItem{}).Where("enabled = ?", true)
	if category := strings.TrimSpace(filter.Category); category != "" {
		query = query.Where("category = ?", category)
	}
	if keyword := strings.ToLower(strings.TrimSpace(filter.Query)); keyword != "" {
		like := "%" + keyword + "%"
		query = query.Where(
			"LOWER(name) LIKE ? OR LOWER(description) LIKE ? OR LOWER(category_name) LIKE ?",
			like, like, like,
		)
	}
	var experts []models.SaAIExpertItem
	if err := query.Order("category asc, id asc").Find(&experts).Error; err != nil {
		return nil, err
	}
	if experts == nil {
		experts = []models.SaAIExpertItem{}
	}
	return experts, nil
}

func (s *SessionService) GetExpert(identity string) (*models.SaAIExpertItem, error) {
	var expert models.SaAIExpertItem
	if err := models.DBService.Where("identity = ? AND enabled = ?", strings.TrimSpace(identity), true).First(&expert).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, ErrExpertNotFound
		}
		return nil, err
	}
	return &expert, nil
}

func findExpertByIdentity(tx *gorm.DB, identity string) (*models.SaAIExpertItem, error) {
	if strings.TrimSpace(identity) == "" {
		return nil, nil
	}
	var expert models.SaAIExpertItem
	if err := tx.Where("identity = ? AND enabled = ?", identity, true).First(&expert).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, ErrExpertNotFound
		}
		return nil, err
	}
	return &expert, nil
}
