// Shared server-test bootstrap.
//
// The Express app transitively imports every controller at top level, and
// several controllers immediately issue SQL queries (e.g. attachments listing
// during attach-route registration). The simplest reliable way to satisfy
// those is to point DB_PATH at the real, fully-populated dev database
// (data/school.db) so every controller sees the full schema + demo data.
//
// The real DB is the dev DB; tests are read-mostly and use demo accounts.
// We never modify real data — login tests use the seeded admin creds.

const path = require('path');
const fs = require('fs');

function pointAtDevDb() {
  // The worktree may not have a real data/school.db. Fall back to the
  // main checkout's copy if needed.
  let dbFile = path.join(__dirname, '..', 'data', 'school.db');
  if (!fs.existsSync(dbFile)) {
    const mainCheckout = path.resolve(__dirname, '..', '..', '..', 'server', 'data', 'school.db');
    if (fs.existsSync(mainCheckout)) {
      fs.mkdirSync(path.dirname(dbFile), { recursive: true });
      fs.copyFileSync(mainCheckout, dbFile);
    } else {
      throw new Error(`No dev database found at ${dbFile} or ${mainCheckout}`);
    }
  }
  process.env.DB_PATH = dbFile;
}

module.exports = { pointAtDevDb };
