package repository

import (
	"x-agents/server/internal/model"

	"gorm.io/gorm"
)

type ToolRepository struct {
	db *gorm.DB
}

func NewToolRepository(db *gorm.DB) *ToolRepository {
	return &ToolRepository{db: db}
}

// DB 获取数据库连接
func (r *ToolRepository) DB() *gorm.DB {
	return r.db
}

func (r *ToolRepository) Create(tool *model.Tool) error {
	return r.db.Create(tool).Error
}

func (r *ToolRepository) FindAll() ([]model.Tool, error) {
	var tools []model.Tool
	err := r.db.Order("category, name").Find(&tools).Error
	return tools, err
}

func (r *ToolRepository) FindByCategory(category string) ([]model.Tool, error) {
	var tools []model.Tool
	err := r.db.Where("category = ?", category).Order("name").Find(&tools).Error
	return tools, err
}

func (r *ToolRepository) FindByID(id string) (*model.Tool, error) {
	var tool model.Tool
	err := r.db.First(&tool, "id = ?", id).Error
	if err != nil {
		return nil, err
	}
	return &tool, nil
}

func (r *ToolRepository) Update(tool *model.Tool) error {
	return r.db.Save(tool).Error
}

func (r *ToolRepository) Delete(id string) error {
	return r.db.Delete(&model.Tool{}, "id = ?", id).Error
}

func (r *ToolRepository) Count() (int64, error) {
	var count int64
	err := r.db.Model(&model.Tool{}).Count(&count).Error
	return count, err
}

// UpsertBatch 批量upsert工具
func (r *ToolRepository) UpsertBatch(tools []model.Tool) error {
	for _, tool := range tools {
		var existing model.Tool
		err := r.db.First(&existing, "name = ?", tool.Name).Error
		if err == gorm.ErrRecordNotFound {
			if err := r.db.Create(&tool).Error; err != nil {
				return err
			}
		} else if err != nil {
			return err
		} else {
			existing.Description = tool.Description
			existing.Category = tool.Category
			existing.Provider = tool.Provider
			existing.Status = tool.Status
			if err := r.db.Save(&existing).Error; err != nil {
				return err
			}
		}
	}
	return nil
}
