import type { InboxStore } from './store.js';
import type { InboxServerEvents } from './events.js';

/**
 * Periodic prune task — drops every blob whose `expires_at <= now`.
 *
 * Configurable via env vars:
 *   SHADE_INBOX_PRUNE_INTERVAL_MINUTES   (default 5)
 */
export class InboxPruneTask {
  private timer: ReturnType<typeof setInterval> | null = null;
  private running = false;
  private readonly intervalMs: number;

  constructor(
    private readonly store: InboxStore,
    options: {
      intervalMinutes?: number;
      events?: InboxServerEvents;
      logger?: { info: (msg: string, meta?: unknown) => void; error: (msg: string, meta?: unknown) => void };
    } = {},
  ) {
    const minutes = options.intervalMinutes
      ?? Number(process.env.SHADE_INBOX_PRUNE_INTERVAL_MINUTES ?? 5);
    this.intervalMs = minutes * 60 * 1000;
    this.events = options.events;
    this.logger = options.logger ?? null;
  }

  private readonly events: InboxServerEvents | undefined;
  private readonly logger: {
    info: (msg: string, meta?: unknown) => void;
    error: (msg: string, meta?: unknown) => void;
  } | null;

  start(): void {
    if (this.running) return;
    this.running = true;
    this.runOnce().catch((err) =>
      this.logger?.error('Initial inbox prune failed', { error: String(err) }),
    );
    this.timer = setInterval(() => {
      this.runOnce().catch((err) =>
        this.logger?.error('Inbox prune failed', { error: String(err) }),
      );
    }, this.intervalMs);
  }

  stop(): void {
    this.running = false;
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }

  async runOnce(): Promise<number> {
    const removed = await this.store.purgeExpired(Date.now());
    if (removed > 0) {
      this.logger?.info('Inbox prune removed expired blobs', { count: removed });
      this.events?.emit('inbox.expired_purged', { count: removed });
    }
    return removed;
  }

  get isRunning(): boolean {
    return this.running;
  }
}
