import type Database from 'better-sqlite3';
import type { MediaStore } from './MediaStore.js';

export class MediaGc {
  constructor(private db: Database.Database, private store: MediaStore) {}

  async run(): Promise<{ removed: number }> {
    const dirs = await this.store.listNoteDirs();
    // Intentionally does NOT filter `deleted_at IS NULL` — trashed notes still own
    // their media until permanentDelete/emptyTrash. Removing dirs of soft-deleted
    // notes here would defeat restore.
    const rows = this.db.prepare('SELECT id FROM notes').all() as Array<{ id: string }>;
    const known = new Set(rows.map((r) => r.id));
    let removed = 0;
    for (const d of dirs) {
      if (!known.has(d)) { await this.store.deleteNoteDirectory(d); removed += 1; }
    }
    return { removed };
  }
}
