import test from 'node:test';
import assert from 'node:assert/strict';
import { createOpenConfigSettingsWindowHandler } from './config-settings-window';

test('createOpenConfigSettingsWindowHandler focuses existing settings window', () => {
  const calls: string[] = [];
  const existing = {
    isDestroyed: () => false,
    show: () => calls.push('show'),
    focus: () => calls.push('focus'),
    loadFile: () => calls.push('load'),
    on: () => {},
  };

  const open = createOpenConfigSettingsWindowHandler({
    getSettingsWindow: () => existing,
    setSettingsWindow: () => calls.push('set'),
    createSettingsWindow: () => {
      throw new Error('Should not create a second window.');
    },
    settingsHtmlPath: '/tmp/settings.html',
    promoteSettingsWindowAboveOverlay: () => calls.push('promote'),
  });

  assert.equal(open(), true);
  assert.deepEqual(calls, ['show', 'focus', 'promote']);
});

test('createOpenConfigSettingsWindowHandler creates window and clears closed state', () => {
  const calls: string[] = [];
  const handlers: { closed?: () => void } = {};
  const created = {
    isDestroyed: () => false,
    show: () => calls.push('show'),
    focus: () => calls.push('focus'),
    loadFile: (path: string) => calls.push(`load:${path}`),
    on: (event: string, handler: () => void) => {
      if (event === 'closed') handlers.closed = handler;
    },
  };

  const open = createOpenConfigSettingsWindowHandler({
    getSettingsWindow: () => null,
    setSettingsWindow: (window) => calls.push(window ? 'set:window' : 'set:null'),
    createSettingsWindow: () => created,
    settingsHtmlPath: '/tmp/settings.html',
    promoteSettingsWindowAboveOverlay: () => calls.push('promote'),
    onClosed: () => calls.push('on-closed'),
  });

  assert.equal(open(), true);
  assert.deepEqual(calls, ['load:/tmp/settings.html', 'set:window', 'show', 'focus', 'promote']);
  assert.ok(handlers.closed);
  handlers.closed();
  assert.deepEqual(calls.slice(-2), ['set:null', 'on-closed']);
});

test('createOpenConfigSettingsWindowHandler clears failed load window state', async () => {
  const calls: string[] = [];
  const created = {
    isDestroyed: () => false,
    show: () => calls.push('show'),
    focus: () => calls.push('focus'),
    loadFile: (path: string) => {
      calls.push(`load:${path}`);
      return Promise.reject(new Error('missing settings html'));
    },
    on: () => {},
    destroy: () => calls.push('destroy'),
  };

  const open = createOpenConfigSettingsWindowHandler({
    getSettingsWindow: () => null,
    setSettingsWindow: (window) => calls.push(window ? 'set:window' : 'set:null'),
    createSettingsWindow: () => created,
    settingsHtmlPath: '/tmp/missing-settings.html',
  });

  assert.equal(open(), true);
  await new Promise((resolve) => setTimeout(resolve, 0));

  assert.deepEqual(calls, [
    'load:/tmp/missing-settings.html',
    'set:window',
    'show',
    'focus',
    'set:null',
    'destroy',
  ]);
});
