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

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

// ListRoleMappings paginates the external→internal role mapping table.
func (l *ListRoleMappingsLogic) ListRoleMappings(req *types.RoleMappingListQuery) (*types.RoleMappingListData, error) {
	if l.svcCtx.PermissionRoleMapping == 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)
	}
	query := &domperm.ListMappingQuery{
		Offset: req.Offset,
		Limit:  req.Limit,
	}
	if req.Source != "" {
		s := enum.RoleSource(req.Source)
		query.Source = &s
	}
	docs, total, err := l.svcCtx.PermissionRoleMapping.List(l.ctx, actor.TenantID, query)
	if err != nil {
		return nil, err
	}
	out := &types.RoleMappingListData{
		Mappings: make([]types.RoleMappingData, 0, len(docs)),
		Total:    total,
		Offset:   req.Offset,
		Limit:    req.Limit,
	}
	for _, rm := range docs {
		out.Mappings = append(out.Mappings, types.RoleMappingData{
			ID:              rm.ID.Hex(),
			TenantID:        rm.TenantID,
			ExternalSource:  rm.ExternalSource.String(),
			ExternalKey:     rm.ExternalKey,
			InternalRoleID:  rm.InternalRoleID,
			InternalRoleKey: rm.InternalRoleKey,
			CreateAt:        rm.CreateAt,
			UpdateAt:        rm.UpdateAt,
		})
	}
	return out, nil
}
