package system

import (
	"context"

	"kra/internal/biz/system"

	"gorm.io/gorm"
)

type autoCodeTemplateRepo struct {
	db *gorm.DB
}

// NewAutoCodeTemplateRepo 创建自动代码模板仓储
func NewAutoCodeTemplateRepo(db *gorm.DB) system.AutoCodeTemplateRepo {
	return &autoCodeTemplateRepo{db: db}
}

// GetPackageByName 根据包名获取包信息
func (r *autoCodeTemplateRepo) GetPackageByName(ctx context.Context, packageName string) (*system.SysAutoCodePackage, error) {
	var entity system.SysAutoCodePackage
	err := r.db.WithContext(ctx).Where("package_name = ?", packageName).First(&entity).Error
	return &entity, err
}

// CreateApis 批量创建API
func (r *autoCodeTemplateRepo) CreateApis(ctx context.Context, apis []system.SysApi) ([]uint, error) {
	if len(apis) == 0 {
		return nil, nil
	}
	err := r.db.WithContext(ctx).Create(&apis).Error
	if err != nil {
		return nil, err
	}
	ids := make([]uint, len(apis))
	for i, api := range apis {
		ids[i] = api.ID
	}
	return ids, nil
}

// GetMenuByName 根据名称获取菜单
func (r *autoCodeTemplateRepo) GetMenuByName(ctx context.Context, name string) (*system.SysBaseMenu, error) {
	var entity system.SysBaseMenu
	err := r.db.WithContext(ctx).Where("name = ?", name).First(&entity).Error
	return &entity, err
}

// CreateMenu 创建菜单
func (r *autoCodeTemplateRepo) CreateMenu(ctx context.Context, menu *system.SysBaseMenu) error {
	return r.db.WithContext(ctx).Create(menu).Error
}

// CreateExportTemplate 创建导出模板
func (r *autoCodeTemplateRepo) CreateExportTemplate(ctx context.Context, tpl *system.SysExportTemplate) error {
	return r.db.WithContext(ctx).Create(tpl).Error
}

// Repeat 检查是否重复创建
func (r *autoCodeTemplateRepo) Repeat(ctx context.Context, businessDB, structName, abbreviation, pkg string) bool {
	var count int64
	r.db.WithContext(ctx).Model(&system.SysAutoCodeHistory{}).
		Where("struct_name = ? AND package = ?", structName, pkg).
		Or("abbreviation = ? AND package = ?", abbreviation, pkg).
		Count(&count)
	return count > 0
}
