/**
 * Setup file loaded before any test that imports server actions.
 *
 * Reasons:
 *   1. Server actions reach for `lib/prisma` which instantiates a global
 *      PrismaClient against `DATABASE_URL` at module load. Set the env
 *      to a per-test-file SQLite DB BEFORE the import chain wakes Prisma
 *      up, so the actions hit our isolated test DB.
 *   2. `prisma db push` once at startup applies the current schema to
 *      that DB so action queries succeed.
 *
 * Used as `setupFiles` in vitest.config.ts.
 */
import { execFileSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';

const dbPath = path.resolve(
  '/tmp',
  `pow-actions-${process.pid}-${Date.now()}.db`,
);
process.env.DATABASE_URL = `file:${dbPath}`;

execFileSync(
  'npx',
  ['prisma', 'db', 'push', '--skip-generate', '--accept-data-loss'],
  { env: process.env, stdio: 'pipe' },
);

// Expose the path so tests can clean rows between cases or peek at the
// raw DB file if they need to.
;(globalThis as any).__POW_TEST_DB__ = dbPath;

// Best-effort cleanup when the worker exits.
process.on('exit', () => {
  for (const ext of ['', '-journal', '-wal', '-shm']) {
    try {
      fs.unlinkSync(dbPath + ext);
    } catch {
      /* */
    }
  }
});
