package system

import (
	"context"

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

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

const initOrderAuthority = initOrderCasbin + 1

type initAuthority struct{}

func NewInitAuthority() system.SubInitializer {
	return &initAuthority{}
}

func (i *initAuthority) 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.SysAuthority{})
}

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

func (i *initAuthority) InitializerName() string {
	return model.TableNameSysAuthority
}

func (i *initAuthority) InitializeData(ctx context.Context) (context.Context, error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return ctx, system.ErrMissingDBContext
	}
	entities := []model.SysAuthority{
		{AuthorityID: 888, AuthorityName: "普通用户", ParentID: 0, DefaultRouter: "dashboard"},
		{AuthorityID: 9528, AuthorityName: "测试角色", ParentID: 0, DefaultRouter: "dashboard"},
		{AuthorityID: 8881, AuthorityName: "普通用户子角色", ParentID: 888, DefaultRouter: "dashboard"},
	}

	if err := db.Create(&entities).Error; err != nil {
		return ctx, errors.Wrapf(err, "%s表数据初始化失败!", model.TableNameSysAuthority)
	}

	// data authority - 设置数据权限关联
	// 888角色可以查看888、9528、8881的数据
	if err := db.Exec("INSERT INTO sys_data_authority_id (sys_authority_authority_id, data_authority_id_authority_id) VALUES (888, 888), (888, 9528), (888, 8881)").Error; err != nil {
		return ctx, errors.Wrapf(err, "sys_data_authority_id表数据初始化失败!")
	}
	// 9528角色可以查看9528、8881的数据
	if err := db.Exec("INSERT INTO sys_data_authority_id (sys_authority_authority_id, data_authority_id_authority_id) VALUES (9528, 9528), (9528, 8881)").Error; err != nil {
		return ctx, errors.Wrapf(err, "sys_data_authority_id表数据初始化失败!")
	}

	next := context.WithValue(ctx, i.InitializerName(), entities)
	return next, nil
}

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