package repository

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

	"gorm.io/gorm"
)

type MCPRepository struct {
	db *gorm.DB
}

func NewMCPRepository(db *gorm.DB) *MCPRepository {
	return &MCPRepository{db: db}
}

func (r *MCPRepository) DB() *gorm.DB {
	return r.db
}

func (r *MCPRepository) Create(mcp *model.MCP) error {
	return r.db.Create(mcp).Error
}

func (r *MCPRepository) FindAll() ([]model.MCP, error) {
	var mcps []model.MCP
	err := r.db.Order("created_at DESC").Find(&mcps).Error
	return mcps, err
}

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

func (r *MCPRepository) FindByName(name string) (*model.MCP, error) {
	var mcp model.MCP
	err := r.db.First(&mcp, "name = ?", name).Error
	if err != nil {
		return nil, err
	}
	return &mcp, nil
}

func (r *MCPRepository) FindByCategory(category string) ([]model.MCP, error) {
	var mcps []model.MCP
	err := r.db.Where("category = ?", category).Find(&mcps).Error
	return mcps, err
}

func (r *MCPRepository) Update(mcp *model.MCP) error {
	return r.db.Save(mcp).Error
}

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

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