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 AssignUserRoleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAssignUserRoleLogic returns the assign-role logic.
func NewAssignUserRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AssignUserRoleLogic {
	return &AssignUserRoleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// AssignUserRole assigns the requested role to the path-bound UID.
func (l *AssignUserRoleLogic) AssignUserRole(req *types.AssignUserRoleByUIDReq) (*types.UserRoleData, error) {
	if l.svcCtx.PermissionUserRole == 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)
	}
	source := enum.RoleSourceManual
	if req.Source != "" {
		source = enum.RoleSource(req.Source)
	}
	ur, err := l.svcCtx.PermissionUserRole.Assign(l.ctx, &domperm.AssignParam{
		TenantID: actor.TenantID,
		UID:      req.UID,
		RoleID:   req.RoleID,
		Source:   source,
	})
	if err != nil {
		return nil, err
	}
	role, err := l.svcCtx.PermissionRole.Get(l.ctx, actor.TenantID, ur.RoleID)
	if err != nil {
		return nil, err
	}
	return &types.UserRoleData{
		ID:              ur.ID.Hex(),
		TenantID:        ur.TenantID,
		UID:             ur.UID,
		RoleID:          ur.RoleID,
		RoleKey:         role.Key,
		RoleDisplayName: role.DisplayName,
		Source:          ur.Source.String(),
		CreateAt:        ur.CreateAt,
		UpdateAt:        ur.UpdateAt,
	}, nil
}
