import { Injectable } from '@nestjs/common'; import mongoose, { type PipelineStage } from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; export interface StaleAccountCandidate { userId: mongoose.Types.ObjectId; puuid: string; lastRefreshRequestedAt?: Date; } export function buildStaleAccountsPipeline(opts: { olderThan: Date; limit: number; }): PipelineStage[] { return [ { $match: { isActivated: true } }, { $unwind: '$riotAccounts' }, { $match: { $or: [ { 'riotAccounts.lastRefreshRequestedAt': { $exists: false } }, { 'riotAccounts.lastRefreshRequestedAt': { $lt: opts.olderThan } }, ], }, }, { $addFields: { 'riotAccounts.lastRefreshRequestedAtSort': { $ifNull: ['$riotAccounts.lastRefreshRequestedAt', new Date(0)], }, }, }, { $sort: { 'riotAccounts.lastRefreshRequestedAtSort': 1 } }, { $limit: opts.limit }, { $project: { _id: 0, userId: '$_id', puuid: '$riotAccounts.puuid', lastRefreshRequestedAt: '$riotAccounts.lastRefreshRequestedAt', }, }, ]; } @Injectable() export class StaleAccountRepository { constructor(private readonly connectionService: ConnectionService) {} public async findStaleAccounts(opts: { olderThan: Date; limit: number; }): Promise { const UserModel = await this.connectionService.getModel('user'); return UserModel.aggregate( buildStaleAccountsPipeline(opts), ).exec(); } }