import { randomBytes } from 'node:crypto';
import type { PreviewImages } from './preview.ts';

// Предпросмотры в памяти процесса (спека хостинга 7.3): последние max пар, каждая живёт ttlMs; на диск не пишутся.
// Map хранит порядок вставки — первая запись самая старая.
export class PreviewStore {
  private readonly items = new Map<string, { at: number; images: PreviewImages }>();
  private readonly now: () => number;
  private readonly max: number;
  private readonly ttlMs: number;

  constructor(o: { now: () => number; max?: number; ttlMs?: number }) {
    this.now = o.now;
    this.max = o.max ?? 20;
    this.ttlMs = o.ttlMs ?? 15 * 60_000;
  }

  put(images: PreviewImages): string {
    const id = randomBytes(16).toString('base64url');
    this.items.set(id, { at: this.now(), images });
    while (this.items.size > this.max) this.items.delete(this.items.keys().next().value!);
    return id;
  }

  get(id: string, kind: 'plain' | 'grid'): Buffer | null {
    const it = this.items.get(id);
    if (!it) return null;
    if (this.now() - it.at >= this.ttlMs) {
      this.items.delete(id);
      return null;
    }
    return it.images[kind];
  }
}
