import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GlancesConfigFlow, createGlancesDiscoveryDescriptor } from '../../ts/integrations/glances/index.js';

tap.test('matches and validates manual Glances entries', async () => {
  const descriptor = createGlancesDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({ host: '192.168.1.70', name: 'NAS Glances' }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('glances');
  expect(result.candidate?.port).toEqual(61208);

  const validator = descriptor.getValidators()[0];
  const validation = await validator.validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();
  expect(validation.normalizedDeviceId).toEqual('192.168.1.70:61208');
});

tap.test('matches HTTP API candidates and creates config flow output', async () => {
  const descriptor = createGlancesDiscoveryDescriptor();
  const httpMatcher = descriptor.getMatchers()[1];
  const result = await httpMatcher.matches({ url: 'http://nas.local:61208/api/4/all' }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('nas.local');
  expect(result.candidate?.metadata?.apiVersion).toEqual(4);

  const step = await new GlancesConfigFlow().start(result.candidate!, {});
  const done = await step.submit!({ username: 'admin', password: 'secret', apiVersion: '4' });

  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('nas.local');
  expect(done.config?.port).toEqual(61208);
  expect(done.config?.apiVersion).toEqual(4);
  expect(done.config?.username).toEqual('admin');
});

tap.test('rejects candidates without Glances hints or usable data', async () => {
  const descriptor = createGlancesDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({ name: 'Generic service' }, {});
  expect(result.matched).toBeFalse();

  const validation = await descriptor.getValidators()[0].validate({ source: 'manual', name: 'Glances' }, {});
  expect(validation.matched).toBeFalse();
});

export default tap.start();
