import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';

export const TEST_ADMIN_EMAIL = 'owner@test.invalid';
export const TEST_ADMIN_PASSWORD = 'OnlyCoin-Test-Admin!2026';

export function prepareTestRuntime(rootDir, dataDir, extraEnv = {}) {
  fs.mkdirSync(dataDir, { recursive: true });
  const result = spawnSync(process.execPath, ['--no-warnings', 'scripts/test-prepare-runtime.js'], {
    cwd: rootDir,
    env: {
      ...process.env,
      NODE_ENV: 'test',
      DATA_DIR: dataDir,
      AUTH_SECRET: 'onlycoin-test-auth-secret-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
      TEST_ADMIN_EMAIL,
      TEST_ADMIN_PASSWORD,
      ...extraEnv
    },
    encoding: 'utf8'
  });
  assert.equal(result.status, 0, result.stderr || result.stdout || 'Test çalışma alanı hazırlanamadı.');
  return JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1));
}

export function serverTestEnv({ dataDir, port, base, extra = {} }) {
  return {
    ...process.env,
    NODE_ENV: 'test',
    HOST: '127.0.0.1',
    PORT: String(port),
    APP_ORIGIN: base,
    DATA_DIR: dataDir,
    AUTH_SECRET: 'onlycoin-test-auth-secret-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    ...extra
  };
}

export async function registerVerifiedUser(call, base, {
  email,
  username = email.split('@')[0],
  displayName = username,
  password = 'OnlyCoin-User!2026'
}) {
  const registered = await call(base, '/api/auth/register', {
    method: 'POST',
    body: { email, username, displayName, password, confirmPassword: password }
  });
  assert.match(registered.debugVerificationCode || '', /^\d{6}$/);
  const verified = await call(base, '/api/auth/email/verify', {
    method: 'POST',
    body: { email, code: registered.debugVerificationCode }
  });
  assert.ok(verified.token);
  return { registered, verified, token: verified.token, password };
}

export function removeRuntime(dataDir) {
  fs.rmSync(dataDir, { recursive: true, force: true });
}

export function projectRoot(importMetaUrl) {
  return path.resolve(path.dirname(new URL(importMetaUrl).pathname), '../..');
}
