package permission

import (
	"context"

	"gateway/internal/model/permission/domain/enum"
	domperm "gateway/internal/model/permission/domain/usecase"
	"gateway/internal/svc"
	"gateway/internal/types"

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

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

// NewUpdateRoleLogic returns the role updater.
func NewUpdateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRoleLogic {
	return &UpdateRoleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// UpdateRole patches DisplayName and/or Status.
func (l *UpdateRoleLogic) UpdateRole(req *types.UpdateRoleByIDReq) (*types.RoleData, error) {
	if l.svcCtx.PermissionRole == nil {
		return nil, errb.SysNotImplemented("permission module not configured")
	}
	actor, err := ActorFromContext(l.ctx)
	if err != nil {
		return nil, errb.AuthUnauthorized(err.Error()).WithCause(err)
	}
	param := &domperm.UpdateRoleParam{}
	if req.DisplayName != "" {
		display := req.DisplayName
		param.DisplayName = &display
	}
	if req.Status != "" {
		status := enum.Status(req.Status)
		param.Status = &status
	}
	role, err := l.svcCtx.PermissionRole.Update(l.ctx, actor.TenantID, req.ID, param)
	if err != nil {
		return nil, err
	}
	return &types.RoleData{
		ID:          role.ID.Hex(),
		TenantID:    role.TenantID,
		Key:         role.Key,
		DisplayName: role.DisplayName,
		CreatorUID:  role.CreatorUID,
		Status:      role.Status.String(),
		IsSystem:    role.IsSystem,
		CreateAt:    role.CreateAt,
		UpdateAt:    role.UpdateAt,
	}, nil
}
