package system

import (
	"context"

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

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

const initOrderMenuAuthority = initOrderMenu + initOrderAuthority

type initMenuAuthority struct{}

func NewInitMenuAuthority() system.SubInitializer {
	return &initMenuAuthority{}
}

func (i *initMenuAuthority) MigrateTable(ctx context.Context) (context.Context, error) {
	return ctx, nil // do nothing
}

func (i *initMenuAuthority) TableCreated(ctx context.Context) bool {
	return false // always replace
}

func (i *initMenuAuthority) InitializerName() string {
	return "sys_authority_menus"
}

func (i *initMenuAuthority) InitializeData(ctx context.Context) (next context.Context, err error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return ctx, system.ErrMissingDBContext
	}

	authorities, ok := ctx.Value(model.TableNameSysAuthority).([]model.SysAuthority)
	if !ok {
		return ctx, errors.Wrap(system.ErrMissingDependentContext, "创建 [菜单-权限] 关联失败, 未找到权限表初始化数据")
	}

	allMenus, ok := ctx.Value(model.TableNameSysBaseMenu).([]model.SysBaseMenu)
	if !ok {
		return ctx, errors.Wrap(system.ErrMissingDependentContext, "创建 [菜单-权限] 关联失败, 未找到菜单表初始化数据")
	}
	next = ctx

	// 构建菜单ID映射
	menuMap := make(map[int64]model.SysBaseMenu)
	for _, menu := range allMenus {
		menuMap[menu.ID] = menu
	}

	// 为不同角色分配不同权限
	// 1. 超级管理员角色(888) - 拥有所有菜单权限
	var menuIDs888 []int64
	for _, menu := range allMenus {
		menuIDs888 = append(menuIDs888, menu.ID)
	}
	for _, menuID := range menuIDs888 {
		if err = db.Exec("INSERT INTO sys_authority_menus (sys_authority_authority_id, sys_base_menu_id) VALUES (?, ?)", authorities[0].AuthorityID, menuID).Error; err != nil {
			return next, errors.Wrap(err, "为超级管理员分配菜单失败")
		}
	}

	// 2. 测试角色(9528) - 仅拥有基础功能菜单
	var menu9528 []int64
	for _, menu := range allMenus {
		if menu.ParentID == 0 && (menu.Name == "dashboard" || menu.Name == "about" || menu.Name == "person" || menu.Name == "state") {
			menu9528 = append(menu9528, menu.ID)
		}
	}
	for _, menuID := range menu9528 {
		if err = db.Exec("INSERT INTO sys_authority_menus (sys_authority_authority_id, sys_base_menu_id) VALUES (?, ?)", authorities[1].AuthorityID, menuID).Error; err != nil {
			return next, errors.Wrap(err, "为测试角色分配菜单失败")
		}
	}

	// 3. 普通用户子角色(8881) - 拥有部分菜单权限
	var menu8881 []int64
	// 添加所有父级菜单
	for _, menu := range allMenus {
		if menu.ParentID == 0 {
			menu8881 = append(menu8881, menu.ID)
		}
	}
	// 添加部分子菜单
	for _, menu := range allMenus {
		parentName := ""
		if menu.ParentID > 0 {
			if parent, exists := menuMap[menu.ParentID]; exists {
				parentName = parent.Name
			}
		}
		if menu.ParentID > 0 && (parentName == "systemTools" || parentName == "example") {
			menu8881 = append(menu8881, menu.ID)
		}
	}
	for _, menuID := range menu8881 {
		if err = db.Exec("INSERT INTO sys_authority_menus (sys_authority_authority_id, sys_base_menu_id) VALUES (?, ?)", authorities[2].AuthorityID, menuID).Error; err != nil {
			return next, errors.Wrap(err, "为普通用户子角色分配菜单失败")
		}
	}

	return next, nil
}

func (i *initMenuAuthority) DataInserted(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return false
	}
	var count int64
	if err := db.Table("sys_authority_menus").Where("sys_authority_authority_id = ?", 8881).Count(&count).Error; err != nil {
		return false
	}
	return count > 0
}
