package permission

import (
	"context"

	"gateway/internal/svc"
	"gateway/internal/types"

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

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

// NewListUserRolesLogic returns the user-role lister.
func NewListUserRolesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListUserRolesLogic {
	return &ListUserRolesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// ListUserRoles returns the role assignments for the path-bound UID.
func (l *ListUserRolesLogic) ListUserRoles(req *types.ListUserRolesReq) (*types.UserRoleListData, 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)
	}
	rows, err := l.svcCtx.PermissionUserRole.List(l.ctx, actor.TenantID, req.UID)
	if err != nil {
		return nil, err
	}
	out := &types.UserRoleListData{UserRoles: make([]types.UserRoleData, 0, len(rows))}
	for _, summary := range rows {
		out.UserRoles = append(out.UserRoles, types.UserRoleData{
			ID:              summary.ID.Hex(),
			TenantID:        summary.TenantID,
			UID:             summary.UID,
			RoleID:          summary.RoleID,
			RoleKey:         summary.RoleKey,
			RoleDisplayName: summary.RoleDisplayName,
			Source:          summary.Source.String(),
			CreateAt:        summary.CreateAt,
			UpdateAt:        summary.UpdateAt,
		})
	}
	return out, nil
}
