#!/usr/bin/env node
/**
 * Verify JSON -> Database migration counts
 */

const fs = require('fs');
const path = require('path');
const { initDatabase, getDatabase, closeDatabase } = require('../src/database/connection');
const { initEncryption } = require('../src/utils/encryption');
const { STATE_DIR, DB_PATH, KEY_FILE } = require('../src/database/config');

function loadJson(filePath, fallback) {
  try {
    const raw = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(raw || JSON.stringify(fallback));
  } catch (_) {
    return fallback;
  }
}

function resolveKey() {
  if (process.env.DATABASE_ENCRYPTION_KEY) return process.env.DATABASE_ENCRYPTION_KEY.trim();
  if (KEY_FILE && fs.existsSync(KEY_FILE)) {
    const key = fs.readFileSync(KEY_FILE, 'utf8').trim();
    if (key) {
      process.env.DATABASE_ENCRYPTION_KEY = key;
      return key;
    }
  }
  return '';
}

function main() {
  const key = resolveKey();
  if (!key) {
    console.error('❌ DATABASE_ENCRYPTION_KEY not set (and no key file found).');
    process.exit(1);
  }

  initEncryption(key);
  const useSqlcipher = process.env.DATABASE_USE_SQLCIPHER !== '0' && process.env.DATABASE_USE_SQLCIPHER !== 'false';
  initDatabase(DB_PATH, {
    sqlcipherKey: useSqlcipher ? key : null,
    cipherCompatibility: process.env.DATABASE_CIPHER_COMPAT || 4,
    kdfIter: process.env.DATABASE_KDF_ITER || 64000
  });

  const db = getDatabase();
  const now = Date.now();

  const usersJson = loadJson(path.join(STATE_DIR, 'users.json'), []);
  const sessionsJson = loadJson(path.join(STATE_DIR, 'user-sessions.json'), {});
  const affiliatesJson = loadJson(path.join(STATE_DIR, 'affiliates.json'), []);

  const usersDb = db.prepare('SELECT COUNT(*) as count FROM users').get().count;
  const sessionsDb = db.prepare('SELECT COUNT(*) as count FROM sessions WHERE expires_at > ?').get(now).count;
  const affiliatesDb = db.prepare('SELECT COUNT(*) as count FROM affiliate_accounts').get().count;

  const activeJsonSessions = Object.values(sessionsJson || {}).filter((session) => session?.expiresAt && session.expiresAt > now).length;

  console.log('Migration verification:');
  console.log(`  Users: JSON=${Array.isArray(usersJson) ? usersJson.length : 0} DB=${usersDb}`);
  console.log(`  Sessions (active): JSON=${activeJsonSessions} DB=${sessionsDb}`);
  console.log(`  Affiliates: JSON=${Array.isArray(affiliatesJson) ? affiliatesJson.length : 0} DB=${affiliatesDb}`);

  closeDatabase();
}

main();
