import { db, load } from './setup.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';

const { getSetting, getBooleanSetting, getStringSetting, updateSettings, effectiveTrustedOrigins } = await load('../models/settingsModel.js');
const { resolvePowerShellExecutable, powerShellSpawnFailureLines } = await load('../services/powershellRunner.js');

test('unpinned settings seed as editable defaults', () => {
  // No SERVER_FQDN env var is set in the test environment, so server_fqdn is a
  // default-sourced, admin-editable setting.
  const source = db.prepare('SELECT source FROM settings WHERE key = ?').get('server_fqdn')?.source;
  assert.equal(source, 'default');
});

test('structural settings are env-pinned and locked', () => {
  const source = db.prepare('SELECT source FROM settings WHERE key = ?').get('database_path')?.source;
  assert.equal(source, 'env');
});

test('updateSettings persists editable keys but rejects env-pinned keys', () => {
  updateSettings({ server_fqdn: 'https://posh.example.com', database_path: '/evil/path.sqlite' });
  assert.equal(getSetting('server_fqdn'), 'https://posh.example.com');
  // The env-pinned database_path must be unchanged.
  assert.notEqual(getSetting('database_path'), '/evil/path.sqlite');
});

test('allow_script_execution is readable as an effective boolean', () => {
  updateSettings({ allow_script_execution: 'false' });
  assert.equal(getBooleanSetting('allow_script_execution', true), false);
  updateSettings({ allow_script_execution: 'true' });
  assert.equal(getBooleanSetting('allow_script_execution', false), true);
});

test('powershell_bin config is used by the runner at execution time', () => {
  updateSettings({ powershell_bin: 'powershell.exe' });
  assert.equal(getStringSetting('powershell_bin', 'pwsh'), 'powershell.exe');
  assert.equal(resolvePowerShellExecutable(), 'powershell.exe');
});

test('PowerShell spawn failures include operator guidance', () => {
  const lines = powerShellSpawnFailureLines({ code: 'ENOENT', message: 'spawn pwsh ENOENT' }, 'pwsh');
  assert.ok(lines.some((line) => line.includes('configured PowerShell executable "pwsh"')));
  assert.ok(lines.some((line) => line.includes('Config > PowerShell Binary')));
  assert.ok(lines.some((line) => line.includes('powershell.exe')));
});

test('effectiveTrustedOrigins merges admin edits with built-in defaults', () => {
  updateSettings({ trusted_origins: 'https://ops.example.com' });
  const origins = effectiveTrustedOrigins();
  assert.ok(origins.includes('https://ops.example.com'));
  assert.ok(origins.includes('http://localhost:3000'));
});
