package admin_menu

import (
	"context"

	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"
	"tydata-server/common/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteMenuLogic {
	return &DeleteMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteMenuLogic) DeleteMenu(req *types.DeleteMenuReq) (resp *types.DeleteMenuResp, err error) {
	// 1. 参数验证
	if req.Id <= 0 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"菜单ID必须大于0, id: %d", req.Id)
	}

	// 2. 查询菜单是否存在
	menu, err := l.svcCtx.AdminMenuModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查找菜单失败, err: %v, id: %d", err, req.Id)
	}

	// 3. 检查是否有子菜单
	childMenuBuilder := l.svcCtx.AdminMenuModel.SelectBuilder().Where("pid = ?", req.Id)
	childMenus, err := l.svcCtx.AdminMenuModel.FindAll(l.ctx, childMenuBuilder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询子菜单失败, err: %v, parent_id: %d", err, req.Id)
	}
	if len(childMenus) > 0 {
		return nil, errors.Wrapf(xerr.NewErrMsg("该菜单下还有子菜单，无法删除"),
			"该菜单下还有子菜单，无法删除, id: %d", req.Id)
	}

	// 4. 检查是否有角色关联该菜单
	roleMenuBuilder := l.svcCtx.AdminRoleMenuModel.SelectBuilder().Where("menu_id = ?", req.Id)
	roleMenus, err := l.svcCtx.AdminRoleMenuModel.FindAll(l.ctx, roleMenuBuilder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询角色菜单关联失败, err: %v, menu_id: %d", err, req.Id)
	}
	if len(roleMenus) > 0 {
		return nil, errors.Wrapf(xerr.NewErrMsg("该菜单已被角色使用，无法删除"),
			"该菜单已被角色使用，无法删除, id: %d", req.Id)
	}

	// 5. 执行软删除
	err = l.svcCtx.AdminMenuModel.DeleteSoft(l.ctx, nil, menu)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"删除菜单失败, err: %v, id: %d", err, req.Id)
	}

	// 6. 返回成功结果
	return &types.DeleteMenuResp{Success: true}, nil
}
