import fs from 'node:fs';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, '..');
const env = { ...process.env, NODE_ENV: 'test' };
const releaseTestFiles = ['data/onlycoin-test.db', 'data/onlycoin-test.db-wal', 'data/onlycoin-test.db-shm', 'data/installed.json', 'data/install.token'];
for (const relative of releaseTestFiles) { try { fs.rmSync(path.join(rootDir, relative), { force: true }); } catch {} }

const syntaxFiles = [
  'server/src/server.js',
  'server/src/main.js',
  'server/src/config.js',
  'server/src/env.js',
  'server/src/installer.js',
  'server/src/admin-auth.js',
  'server/src/database-health.js',
  'server/src/migrations.js',
  'server/src/ledger.js',
  'server/src/identity.js',
  'server/src/wallets.js',
  'server/src/presale.js',
  'server/src/distribution.js',
  'server/src/email.js',
  'server/src/secrets.js',
  'scripts/start.js',
  'scripts/test-prepare-runtime.js',
  'scripts/repair-database.js',
  'scripts/backup-database.js',
  'apps/installer/app.js',
  'apps/website/app.js',
  'apps/game/app.js',
  'apps/admin/admin.js'
];

const testFiles = [
  'server/test/core.test.js',
  'server/test/payments.test.js',
  'server/test/payment-http.test.js',
  'server/test/startup.test.js',
  'server/test/database-health.test.js',
  'server/test/wheel-cms-http.test.js',
  'server/test/final-v1-http.test.js',
  'server/test/manual-distribution-http.test.js',
  'server/test/installer-http.test.js'
];

const commands = [
  ...syntaxFiles.map((file) => ['--check', file]),
  ['--no-warnings', '--test', '--test-concurrency=1', ...testFiles]
];

for (const args of commands) {
  const code = await new Promise((resolve, reject) => {
    const child = spawn(process.execPath, args, { cwd: rootDir, env, stdio: 'inherit' });
    child.once('error', reject);
    child.once('exit', resolve);
  });
  if (code !== 0) process.exit(code ?? 1);
}
for (const relative of releaseTestFiles) { try { fs.rmSync(path.join(rootDir, relative), { force: true }); } catch {} }
console.log('\nTüm OnlyCoin üretim kurulumu ve uygulama kontrolleri başarıyla tamamlandı.');
