import * as fs from 'node:fs';

export class WalWatcher {
  private timer: NodeJS.Timeout | null = null;
  private lastMtime = 0;

  constructor(
    private readonly mainDbPath: string,
    private readonly onChange: () => Promise<void>,
    private readonly intervalMs = 500,
  ) {}

  get walPath(): string { return this.mainDbPath + '-wal'; }

  start(): void {
    if (this.timer) return;
    this.lastMtime = this.readMtime();
    this.timer = setInterval(() => this.tick().catch(() => void 0), this.intervalMs);
  }

  stop(): void {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  }

  private readMtime(): number {
    try { return fs.statSync(this.walPath).mtimeMs; }
    catch { return 0; }
  }

  private async tick(): Promise<void> {
    const m = this.readMtime();
    if (m === 0 || m === this.lastMtime) return;
    this.lastMtime = m;
    await this.onChange();
  }
}
