import fs from 'node:fs';
import path from 'node:path';
import { config } from '../server/src/config.js';
import { closeDb, getDb, setSetting, withTransaction } from '../server/src/db.js';
import { createInitialAdmin } from '../server/src/admin-auth.js';
import { nowIso, uuid } from '../server/src/utils.js';
import { postTransferInTx } from '../server/src/ledger.js';

if (config.environment !== 'test') {
  throw new Error('test-prepare-runtime.js yalnızca NODE_ENV=test ile çalıştırılabilir.');
}

const adminEmail = String(process.env.TEST_ADMIN_EMAIL || 'owner@test.invalid').trim().toLowerCase();
const adminPassword = String(process.env.TEST_ADMIN_PASSWORD || 'OnlyCoin-Test-Admin!2026');
const adminName = String(process.env.TEST_ADMIN_NAME || 'OnlyCoin Test Owner');

fs.mkdirSync(config.dataDir, { recursive: true });
const db = getDb();

withTransaction(db, () => {
  db.prepare('DELETE FROM sessions').run();
  db.prepare('DELETE FROM admin_users').run();
});

const admin = createInitialAdmin(db, {
  email: adminEmail,
  name: adminName,
  password: adminPassword,
  confirmPassword: adminPassword
}, '127.0.0.1');

const settings = {
  app_name: 'OnlyCoin Test',
  account_registration_enabled: true,
  email_registration_enabled: true,
  account_require_email_verification: true,
  email_verification_required: true,
  smtp_enabled: false,
  initial_points: 0,
  presale_enabled: false,
  deposit_enabled: false,
  withdrawal_enabled: false,
  distribution_enabled: false,
  purchases_enabled: false,
  fiat_payments_enabled: false,
  bank_transfer_enabled: false,
  crypto_funding_enabled: false,
  crypto_payment_for_goods_enabled: false,
  installation_id: `test-${uuid()}`,
  installed_at: nowIso()
};
for (const [key, value] of Object.entries(settings)) setSetting(db, key, value);

const treasuryFunding = Number.parseInt(process.env.TEST_TOKEN_TREASURY_AMOUNT || '0', 10);
if (Number.isSafeInteger(treasuryFunding) && treasuryFunding > 0) {
  withTransaction(db, () => postTransferInTx(db, {
    fromAccountId: 'sys-token-issuance',
    toAccountId: 'sys-token-treasury',
    amount: treasuryFunding,
    type: 'test_treasury_funding',
    ref: 'test-runtime',
    idempotencyKey: 'test-runtime-token-treasury-funding',
    metadata: { environment: 'test' }
  }));
}

const metadata = {
  installed: true,
  installationId: settings.installation_id,
  version: config.appVersion,
  installedAt: settings.installed_at,
  appOrigin: process.env.APP_ORIGIN || 'http://127.0.0.1',
  appName: 'OnlyCoin Test',
  adminEmail
};
fs.writeFileSync(config.installLockPath, JSON.stringify(metadata, null, 2), { encoding: 'utf8', mode: 0o600 });
try { fs.chmodSync(config.installLockPath, 0o600); } catch { /* Windows */ }
fs.rmSync(config.installTokenPath, { force: true });

console.log(JSON.stringify({ ok: true, dataDir: config.dataDir, dbPath: config.dbPath, admin }));
closeDb();
