/* test/_setup.js
 *
 * Each test file requires this and gets:
 *   - a fresh in-memory sqlite via setupFreshDb()
 *   - a seeded superadmin (id=1, email=admin@test.local, password=TestPass!1234)
 *
 * Tests should `require('./_setup')` BEFORE requiring any model/service
 * that touches the DB.
 */

'use strict';

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

// Build a temp directory to act as the data root
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ncii-test-'));
process.env.DB_PATH = path.join(tmp, 'test.sqlite');
process.env.SESSION_SECRET = 'x'.repeat(64);
process.env.PUBLIC_BASE_URL = 'http://test.local';
process.env.NODE_ENV = 'test';
process.env.NCII_REQUIRE_SUPERADMIN_2FA = '0';
process.env.NCII_DEEP_DISCOVERY_TEST_MODE = '0';
process.env.NCII_ALERT_TEST_MODE = '0';

const dbMod = require('../config/db');
const { db, init } = dbMod;
init();
const User = require('../models/user');
const Takedown = require('../models/takedown');

const TEST_ADMIN = { id: 1, email: 'admin@test.local', password: 'TestPass!1234', name: 'Test Admin', role: 'superadmin' };

function seedAdmin() {
  // Idempotent — drop + recreate
  db.prepare('DELETE FROM users WHERE email = ?').run(TEST_ADMIN.email);
  User.create({ email: TEST_ADMIN.email, name: TEST_ADMIN.name, password: TEST_ADMIN.password, role: 'superadmin' });
}

function setupFreshDb() {
  // Drop user-scoped tables; keep schema. Cheaper than re-init.
  const tables = ['findings', 'takedowns', 'cases', 'alerts', 'api_keys', 'api_tokens', 'usage_log', 'audit_log', 'sessions', 'user_2fa', 'user_known_ips', 'login_attempts', 'email_templates', 'keyword_lists', 'takedown_jobs', 'webhook_events', 'alert_prefs', 'case_discovery_scans', 'platform_contacts',
    'webhooks', 'webhook_deliveries', 'link_health_checks', 'monitored_urls', 'email_digest_subscriptions', 'email_transport', 'finding_classifications', 'takedown_notes', 'trusted_devices'];
  for (const t of tables) {
    try { db.exec(`DELETE FROM ${t}`); } catch (_) { /* table may not exist */ }
  }
  seedAdmin();
  return { db, user: TEST_ADMIN };
}

function teardown() {
  try { fs.rmSync(tmp, { recursive: true, force: true }); } catch (_) {}
}

module.exports = { setupFreshDb, teardown, TEST_ADMIN, db };
