/**
 * Removes uploaded files that no attachment row points at any more.
 *
 * Wiping the database leaves every uploaded file behind — db:truncate empties
 * the attachment table but never touches the disk — and so does deleting a
 * receipt or a reading. Those files are unreachable either way: a download
 * resolves an attachment row first, so nothing can open them again.
 *
 * Dry run by default: it prints what it would remove and removes nothing.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/prune-orphan-uploads.ts
 *      …the same with a trailing `delete` to actually remove them.
 */
import { PrismaService } from '../src/prisma/prisma.service';
import * as fs from 'fs';
import * as path from 'path';
const p = new PrismaService();
const root = process.env.STORAGE_LOCAL_ROOT ?? path.resolve(__dirname, '..', 'storage');
const dir = path.join(root, 'uploads');

/** Storage is sharded two characters deep (uploads/ac/<uuid>.png), so a flat
 *  readdir sees shard directories, not files — walking is the only honest scan. */
function walk(d: string, base = ''): string[] {
  if (!fs.existsSync(d)) return [];
  return fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => {
    const rel = base ? `${base}/${e.name}` : e.name;
    return e.isDirectory() ? walk(path.join(d, e.name), rel) : [rel];
  });
}

(async () => {
  const rows = await p.attachment.findMany({ select: { storageKey: true, filename: true } });
  // Statements sent to tenants keep their PDF in the same store, without an attachment row.
  const sent = await p.sentStatement.findMany({ select: { storageKey: true } });
  const keep = new Set([...rows, ...sent].map((r) => r.storageKey.replace(/^\/+/, '')));
  console.log(`attachment rows in the DB: ${rows.length}`);
  for (const r of rows) console.log(`   referenced: ${r.storageKey}  (${r.filename})`);

  const files = walk(dir);
  const orphans = files.filter((f) => !keep.has(f));
  const bytes = orphans.reduce((s, f) => s + fs.statSync(path.join(dir, f)).size, 0);
  console.log(`\nfiles on disk: ${files.length}, referenced: ${files.length - orphans.length}, orphaned: ${orphans.length} (${bytes} bytes)`);
  for (const f of orphans.slice(0, 20)) console.log('   orphan:', f);

  if (process.argv[2] === 'delete') {
    for (const f of orphans) fs.unlinkSync(path.join(dir, f));
    // Sweep the shard directories the deletions emptied.
    for (const d of fs.readdirSync(dir, { withFileTypes: true })) {
      const full = path.join(dir, d.name);
      if (d.isDirectory() && fs.readdirSync(full).length === 0) fs.rmdirSync(full);
    }
    console.log(`\ndeleted ${orphans.length} orphaned file(s); ${walk(dir).length} file(s) remain`);
  } else {
    console.log('\n(dry run — pass "delete" to remove them)');
  }
  await p.$disconnect();
})();
