package system

import (
	"context"

	"kra/internal/biz/system"

	"gorm.io/gorm"
)

type autoCodeHistoryRepo struct {
	db *gorm.DB
}

// NewAutoCodeHistoryRepo 创建自动代码历史仓储
func NewAutoCodeHistoryRepo(db *gorm.DB) system.AutoCodeHistoryRepo {
	return &autoCodeHistoryRepo{db: db}
}

// First 根据id获取meta信息
func (r *autoCodeHistoryRepo) First(ctx context.Context, id uint) (string, error) {
	var meta string
	err := r.db.WithContext(ctx).Model(&system.SysAutoCodeHistory{}).
		Where("id = ?", id).
		Pluck("request", &meta).Error
	return meta, err
}

// Delete 删除历史记录
func (r *autoCodeHistoryRepo) Delete(ctx context.Context, id uint) error {
	return r.db.WithContext(ctx).Where("id = ?", id).Delete(&system.SysAutoCodeHistory{}).Error
}

// GetList 获取历史记录列表
func (r *autoCodeHistoryRepo) GetList(ctx context.Context, page, pageSize int) ([]system.SysAutoCodeHistory, int64, error) {
	var list []system.SysAutoCodeHistory
	var total int64

	db := r.db.WithContext(ctx).Model(&system.SysAutoCodeHistory{})
	err := db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	offset := (page - 1) * pageSize
	err = db.Offset(offset).Limit(pageSize).Order("updated_at desc").Find(&list).Error
	return list, total, err
}

// GetByID 根据ID获取历史记录
func (r *autoCodeHistoryRepo) GetByID(ctx context.Context, id uint) (*system.SysAutoCodeHistory, error) {
	var history system.SysAutoCodeHistory
	err := r.db.WithContext(ctx).Where("id = ?", id).First(&history).Error
	return &history, err
}

// UpdateFlag 更新标记
func (r *autoCodeHistoryRepo) UpdateFlag(ctx context.Context, id uint, flag int) error {
	return r.db.WithContext(ctx).Model(&system.SysAutoCodeHistory{}).
		Where("id = ?", id).
		Update("flag", flag).Error
}

// DropTable 删除表
func (r *autoCodeHistoryRepo) DropTable(ctx context.Context, businessDB, tableName string) error {
	// 注意：这里简化处理，实际应该支持多数据库
	return r.db.WithContext(ctx).Exec("DROP TABLE IF EXISTS " + tableName).Error
}

// Create 创建历史记录
func (r *autoCodeHistoryRepo) Create(ctx context.Context, history *system.SysAutoCodeHistory) error {
	return r.db.WithContext(ctx).Create(history).Error
}

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