const fs = require('node:fs');
const path = require('node:path');
const { JSDOM } = require('jsdom');
const test = require('node:test');
const assert = require('node:assert/strict');

const source = fs.readFileSync(path.join(__dirname, '..', 'js', 'core', 'credentials.js'), 'utf8');

function buildDnsCredentialUi() {
  const dom = new JSDOM('<!doctype html><body><button id="manage-tokens"></button></body>', {
    url: 'https://status.sami/',
    runScripts: 'outside-only',
  });
  const { window } = dom;
  const local = new Map();
  const session = new Map();
  window.SITE = { dnsServers: { dns1: { name: 'Primary DNS' } } };
  window.injectModal = (_id, html) => window.document.body.insertAdjacentHTML('beforeend', html);
  window.safeGet = key => local.get(key) || null;
  window.safeSet = (key, value) => local.set(key, value);
  window.safeRemove = key => local.delete(key);
  window.safeSessionGet = key => session.get(key) || null;
  window.safeSessionSet = (key, value) => session.set(key, value);
  window.closeModal = () => {};
  window.confirm = () => true;
  window.TextEncoder = TextEncoder;
  window.setTimeout = () => 1;
  window.eval(source);
  window.document.getElementById('manage-tokens').click();
  return { window, local };
}

test('failed DNS credential save never populates browser cache or success UI', async () => {
  const { window, local } = buildDnsCredentialUi();
  window.secureFetch = async () => ({
    ok: false,
    status: 500,
    json: async () => ({ success: false, error: 'DNS vault rejected' }),
  });
  window.document.getElementById('dns1-admin-username').value = 'dns-admin';
  window.document.getElementById('dns1-admin-token').value = 'dns-password';
  window.document.getElementById('token-save').click();
  await new Promise(resolve => setTimeout(resolve, 20));

  assert.equal(local.has('dns1-admin-username-enc'), false);
  assert.equal(local.has('dns1-admin-token-enc'), false);
  assert.match(window.document.getElementById('dns1-token-status').textContent, /DNS vault rejected/);
  assert.equal(window.document.getElementById('dns1-token-status').classList.contains('success'), false);
});

test('failed DNS credential clear preserves cached state and shows error', async () => {
  const { window, local } = buildDnsCredentialUi();
  local.set('dns1-admin-username-enc', 'existing-user');
  local.set('dns1-admin-token-enc', 'existing-password');
  window.secureFetch = async () => ({
    ok: true,
    status: 200,
    json: async () => ({ message: 'ambiguous response' }),
  });
  window.document.getElementById('token-clear-all').click();
  await new Promise(resolve => setTimeout(resolve, 20));

  assert.equal(local.has('dns1-admin-username-enc'), true);
  assert.equal(local.has('dns1-admin-token-enc'), true);
  assert.match(window.document.getElementById('dns1-token-status').textContent, /DNS credential removal failed/);
  assert.equal(window.document.getElementById('dns1-token-status').classList.contains('success'), false);
});
