package permission

import (
	"context"

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

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

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

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

// ListRoles lists every role in the caller's tenant (including system roles).
func (l *ListRolesLogic) ListRoles() (*types.RoleListData, 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)
	}
	roles, err := l.svcCtx.PermissionRole.List(l.ctx, actor.TenantID)
	if err != nil {
		return nil, err
	}
	out := &types.RoleListData{Roles: make([]types.RoleData, 0, len(roles))}
	for _, role := range roles {
		out.Roles = append(out.Roles, 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,
		})
	}
	return out, nil
}
