package permission

import (
	"context"

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

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

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

// NewGetRolePermissionsLogic returns the role-permission reader.
func NewGetRolePermissionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRolePermissionsLogic {
	return &GetRolePermissionsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// GetRolePermissions reads the permission catalog entries currently
// assigned to the role.
func (l *GetRolePermissionsLogic) GetRolePermissions(req *types.GetRolePermissionsByIDReq) (*types.RolePermissionsListData, error) {
	if l.svcCtx.PermissionRolePermission == 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)
	}
	perms, err := l.svcCtx.PermissionRolePermission.List(l.ctx, actor.TenantID, req.ID)
	if err != nil {
		return nil, err
	}
	out := &types.RolePermissionsListData{Permissions: make([]types.PermissionNode, 0, len(perms))}
	for _, perm := range perms {
		out.Permissions = append(out.Permissions, types.PermissionNode{
			ID:          perm.ID.Hex(),
			Parent:      perm.Parent,
			Name:        perm.Name,
			HTTPMethods: perm.HTTPMethods,
			HTTPPath:    perm.HTTPPath,
			Status:      perm.Status.String(),
			Type:        perm.Type.String(),
		})
	}
	return out, nil
}
