const test = require('node:test')
const assert = require('node:assert/strict')

const { buildDesktopLaunchEnv } = require('../dist/desktop-launch-env.js')

test('removes vault-scoped managed secrets and runtime env before launching a child process', () => {
  const env = {
    ARCHE_CONNECTOR_OAUTH_STATE_SECRET: 'oauth-secret',
    ARCHE_DATA_DIR: '/tmp/vault-a',
    ARCHE_DESKTOP_API_TOKEN: 'desktop-token',
    ARCHE_DESKTOP_MANAGED_CONNECTOR_OAUTH_STATE_SECRET: '1',
    ARCHE_DESKTOP_MANAGED_ENCRYPTION_KEY: '1',
    ARCHE_DESKTOP_VAULT_ID: 'vault-a',
    ARCHE_DESKTOP_VAULT_NAME: 'Vault A',
    ARCHE_DESKTOP_VAULT_PATH: '/tmp/vault-a',
    ARCHE_DESKTOP_WEB_PORT: '3000',
    ARCHE_ENCRYPTION_KEY: 'encryption-key',
    ARCHE_GATEWAY_TOKEN_SECRET: 'gateway-secret',
    ARCHE_OPENCODE_DATA_DIR: '/tmp/vault-a/.runtime/opencode',
    NODE_ENV: 'production',
    PATH: '/usr/bin',
  }

  const launchEnv = buildDesktopLaunchEnv(env)

  assert.equal(launchEnv.ARCHE_CONNECTOR_OAUTH_STATE_SECRET, undefined)
  assert.equal(launchEnv.ARCHE_DATA_DIR, undefined)
  assert.equal(launchEnv.ARCHE_DESKTOP_API_TOKEN, undefined)
  assert.equal(launchEnv.ARCHE_DESKTOP_MANAGED_CONNECTOR_OAUTH_STATE_SECRET, undefined)
  assert.equal(launchEnv.ARCHE_DESKTOP_MANAGED_ENCRYPTION_KEY, undefined)
  assert.equal(launchEnv.ARCHE_DESKTOP_VAULT_ID, undefined)
  assert.equal(launchEnv.ARCHE_DESKTOP_VAULT_NAME, undefined)
  assert.equal(launchEnv.ARCHE_DESKTOP_VAULT_PATH, undefined)
  assert.equal(launchEnv.ARCHE_DESKTOP_WEB_PORT, undefined)
  assert.equal(launchEnv.ARCHE_ENCRYPTION_KEY, undefined)
  assert.equal(launchEnv.ARCHE_GATEWAY_TOKEN_SECRET, undefined)
  assert.equal(launchEnv.ARCHE_OPENCODE_DATA_DIR, undefined)
  assert.equal(launchEnv.NODE_ENV, 'production')
  assert.equal(launchEnv.PATH, '/usr/bin')
})

test('preserves explicit secret overrides that were not generated by the desktop runtime', () => {
  const env = {
    ARCHE_CONNECTOR_OAUTH_STATE_SECRET: 'override-secret',
    ARCHE_ENCRYPTION_KEY: 'override-key',
    PATH: '/usr/bin',
  }

  const launchEnv = buildDesktopLaunchEnv(env)

  assert.equal(launchEnv.ARCHE_CONNECTOR_OAUTH_STATE_SECRET, 'override-secret')
  assert.equal(launchEnv.ARCHE_ENCRYPTION_KEY, 'override-key')
  assert.equal(launchEnv.PATH, '/usr/bin')
})

test('does not mutate the parent process env object', () => {
  const env = {
    ARCHE_CONNECTOR_OAUTH_STATE_SECRET: 'oauth-secret',
    ARCHE_ENCRYPTION_KEY: 'encryption-key',
    PATH: '/usr/bin',
  }

  const launchEnv = buildDesktopLaunchEnv(env)

  assert.notEqual(launchEnv, env)
  assert.equal(env.ARCHE_CONNECTOR_OAUTH_STATE_SECRET, 'oauth-secret')
  assert.equal(env.ARCHE_ENCRYPTION_KEY, 'encryption-key')
  assert.equal(env.PATH, '/usr/bin')
})
