import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';

const root = path.resolve(import.meta.dirname, '..');

async function read(relativePath) {
  return fs.readFile(path.join(root, relativePath), 'utf8');
}

test('default server socket uses the local Wegwichtel endpoint', async () => {
  const configSource = await read('src/config.js');
  const envExample = await read('.env.example');
  const serverSource = await read('server.js');
  const apiSource = await read('src/routes/api.js');

  assert.match(configSource, /process\.env\.HOST \|\| '127\.0\.0\.1'/);
  assert.match(configSource, /process\.env\.PORT \|\| '47145'/);
  assert.match(envExample, /^HOST=127\.0\.0\.1$/m);
  assert.match(envExample, /^PORT=47145$/m);
  assert.doesNotMatch(configSource, /instanceName|INSTANCE_NAME/);
  assert.doesNotMatch(envExample, /INSTANCE_NAME/);
  assert.match(serverSource, /Wegwichtel läuft auf http:\/\/\$\{config\.host\}:\$\{config\.port\}/);
  assert.doesNotMatch(apiSource, /instance:/);
});

test('retired internal instance label is absent from authored project files', async () => {
  const extensions = new Set(['.js', '.json', '.md', '.html', '.css', '.env', '.sql', '.gpx', '.svg']);
  const ignoredDirectories = new Set(['node_modules', 'vendor', 'coverage', 'data', 'storage', '.git']);
  const files = [];

  async function collect(directory) {
    for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
      if (entry.isDirectory() && ignoredDirectories.has(entry.name)) continue;
      const absolute = path.join(directory, entry.name);
      if (entry.isDirectory()) await collect(absolute);
      else if (extensions.has(path.extname(entry.name)) || entry.name === '.env.example') files.push(absolute);
    }
  }

  await collect(root);
  const content = (await Promise.all(files.map(file => fs.readFile(file, 'utf8')))).join('\n');
  const retiredLabel = ['at', 'las'].join('');
  assert.doesNotMatch(content, new RegExp(retiredLabel, 'i'));
});

test('runtime route directories keep their repository placeholders', async () => {
  for (const relativePath of [
    'storage/active/routes/.gitkeep',
    'storage/trash/routes/.gitkeep'
  ]) {
    const stat = await fs.stat(path.join(root, relativePath));
    assert.ok(stat.isFile(), `${relativePath} fehlt`);
  }
});
