package system

import (
	"context"

	"kra/internal/biz/system"
	"kra/internal/data/model"

	"github.com/pkg/errors"
	"gorm.io/gorm"
)

const initOrderDict = initOrderCasbin + 1

type initDict struct{}

func NewInitDict() system.SubInitializer {
	return &initDict{}
}

func (i *initDict) MigrateTable(ctx context.Context) (context.Context, error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return ctx, system.ErrMissingDBContext
	}
	return ctx, db.AutoMigrate(&model.SysDictionary{})
}

func (i *initDict) TableCreated(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return false
	}
	return db.Migrator().HasTable(&model.SysDictionary{})
}

func (i *initDict) InitializerName() string {
	return model.TableNameSysDictionary
}

func (i *initDict) InitializeData(ctx context.Context) (next context.Context, err error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return ctx, system.ErrMissingDBContext
	}
	entities := []model.SysDictionary{
		{Name: "性别", Type: "gender", Status: true, Desc: "性别字典"},
		{Name: "数据库int类型", Type: "int", Status: true, Desc: "int类型对应的数据库类型"},
		{Name: "数据库时间日期类型", Type: "time.Time", Status: true, Desc: "数据库时间日期类型"},
		{Name: "数据库浮点型", Type: "float64", Status: true, Desc: "数据库浮点型"},
		{Name: "数据库字符串", Type: "string", Status: true, Desc: "数据库字符串"},
		{Name: "数据库bool类型", Type: "bool", Status: true, Desc: "数据库bool类型"},
	}

	if err = db.Create(&entities).Error; err != nil {
		return ctx, errors.Wrap(err, model.TableNameSysDictionary+"表数据初始化失败!")
	}
	next = context.WithValue(ctx, i.InitializerName(), entities)
	return next, nil
}

func (i *initDict) DataInserted(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return false
	}
	if errors.Is(db.Where("type = ?", "bool").First(&model.SysDictionary{}).Error, gorm.ErrRecordNotFound) {
		return false
	}
	return true
}
