import { rmSync } from 'node:fs';

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function closeVendooDatabase({ failures = [], label = 'Temporäre SQLite-Datenbank' } = {}) {
  try {
    const { db } = await import('../lib/db.mjs');
    if (db?.open) {
      try { db.pragma('wal_checkpoint(TRUNCATE)'); } catch {}
      db.close();
    }
    return true;
  } catch (error) {
    failures.push(`${label} konnte nicht sauber geschlossen werden: ${error.code || error.message}`);
    return false;
  }
}

export async function removeTempDirectory(path, {
  failures = [],
  label = 'Temporärer Testordner',
  settleMs = 100,
  maxRetries = 30,
  retryDelay = 100,
} = {}) {
  if (settleMs > 0) await wait(settleMs);
  try {
    rmSync(path, { recursive: true, force: true, maxRetries, retryDelay });
    return true;
  } catch (error) {
    failures.push(`${label} konnte nicht entfernt werden: ${error.code || error.message} (${path})`);
    return false;
  }
}
