package logic

import (
	"context"
	"fmt"

	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"

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

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

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

func (l *GetRoleDetailLogic) GetRoleDetail(in *system.GetRoleDetailReq) (*system.RoleDetailResp, error) {
	var role sysModel.SundynixRole
	if err := l.svcCtx.DB.Preload("Menus").Where("id = ?", in.Id).First(&role).Error; err != nil {
		return nil, fmt.Errorf("获取角色详情失败: %w", err)
	}

	var menuIds []string
	for _, menu := range role.Menus {
		menuIds = append(menuIds, menu.ID)
	}

	return &system.RoleDetailResp{
		Id:      role.ID,
		Name:    role.Name,
		Code:    role.Code,
		Sort:    int32(role.Sort),
		MenuIds: menuIds,
	}, nil
}
