package repository

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

	"gorm.io/gorm"
)

type SubTableRepository struct {
	db *gorm.DB
}

func NewSubTableRepository(db *gorm.DB) *SubTableRepository {
	return &SubTableRepository{db: db}
}

// Create 创建子表信息
func (r *SubTableRepository) Create(info *model.SubTableInfo) error {
	return r.db.Create(info).Error
}

// FindByID 根据ID查询
func (r *SubTableRepository) FindByID(id string) (*model.SubTableInfo, error) {
	var info model.SubTableInfo
	if err := r.db.Where("id = ?", id).First(&info).Error; err != nil {
		return nil, err
	}
	return &info, nil
}

// FindByDatabaseID 根据数据库ID查询所有子表
func (r *SubTableRepository) FindByDatabaseID(databaseID string) ([]model.SubTableInfo, error) {
	var list []model.SubTableInfo
	if err := r.db.Where("database_id = ?", databaseID).Find(&list).Error; err != nil {
		return nil, err
	}
	return list, nil
}

// Update 更新子表信息
func (r *SubTableRepository) Update(id string, info *model.SubTableInfo) error {
	return r.db.Model(info).Where("id = ?", id).Updates(info).Error
}

// Delete 删除子表信息
func (r *SubTableRepository) Delete(id string) error {
	return r.db.Where("id = ?", id).Delete(&model.SubTableInfo{}).Error
}

// DeleteByDatabaseID 删除数据库下所有子表信息
func (r *SubTableRepository) DeleteByDatabaseID(databaseID string) error {
	return r.db.Where("database_id = ?", databaseID).Delete(&model.SubTableInfo{}).Error
}
