import { Injectable } from '@nestjs/common';

interface StoredRefresh {
  userId: number;
  expiresAt: number;
}

@Injectable()
export class RefreshTokenStoreService {
  private readonly store = new Map<string, StoredRefresh>();
  private cleanupInterval: ReturnType<typeof setInterval> | null = null;

  constructor() {
    this.cleanupInterval = setInterval(() => this.cleanup(), 60_000);
  }

  private cleanup() {
    const now = Date.now();
    for (const [token, data] of this.store.entries()) {
      if (data.expiresAt < now) this.store.delete(token);
    }
  }

  set(token: string, userId: number, expiresAt: number): void {
    this.store.set(token, { userId, expiresAt });
  }

  get(token: string): { userId: number } | null {
    const data = this.store.get(token);
    if (!data || data.expiresAt < Date.now()) return null;
    return { userId: data.userId };
  }

  remove(token: string): void {
    this.store.delete(token);
  }
}
