package repository

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

	"gorm.io/gorm"
)

type SkillRepository struct {
	db *gorm.DB
}

func NewSkillRepository(db *gorm.DB) *SkillRepository {
	return &SkillRepository{db: db}
}

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

func (r *SkillRepository) Create(skill *model.Skill) error {
	return r.db.Create(skill).Error
}

func (r *SkillRepository) FindAll() ([]model.Skill, error) {
	var skills []model.Skill
	err := r.db.Order("skill_type, skill_name").Find(&skills).Error
	return skills, err
}

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

func (r *SkillRepository) FindByType(skillType string) ([]model.Skill, error) {
	var skills []model.Skill
	err := r.db.Where("skill_type = ?", skillType).Order("skill_name").Find(&skills).Error
	return skills, err
}

func (r *SkillRepository) FindByName(skillName string) (*model.Skill, error) {
	var skill model.Skill
	err := r.db.First(&skill, "skill_name = ?", skillName).Error
	if err != nil {
		return nil, err
	}
	return &skill, nil
}

func (r *SkillRepository) Update(skill *model.Skill) error {
	return r.db.Save(skill).Error
}

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

// UpsertBatch 批量upsert skills
func (r *SkillRepository) UpsertBatch(skills []model.Skill) error {
	for _, skill := range skills {
		var existing model.Skill
		err := r.db.First(&existing, "skill_name = ? AND skill_type = ?", skill.SkillName, skill.SkillType).Error
		if err == gorm.ErrRecordNotFound {
			if err := r.db.Create(&skill).Error; err != nil {
				return err
			}
		} else if err != nil {
			return err
		} else {
			existing.SkillDesc = skill.SkillDesc
			existing.Path = skill.Path
			existing.Status = skill.Status
			if err := r.db.Save(&existing).Error; err != nil {
				return err
			}
		}
	}
	return nil
}

// DeleteByType 根据类型删除
func (r *SkillRepository) DeleteByType(skillType string) error {
	return r.db.Where("skill_type = ?", skillType).Delete(&model.Skill{}).Error
}
