import { createServer } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HddtempClient, HddtempIntegration, type IHddtempSnapshot } from '../../ts/integrations/hddtemp/index.js';

const rawData = '|/dev/sda|Samsung SSD 860|39|C||/dev/sdb|WDC WD20EFRX|41|C|';

tap.test('reads hddtemp snapshots from a local TCP daemon and exposes runtime sensors', async () => {
  const server = createServer((socketArg) => socketArg.end(rawData));
  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));

  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const client = new HddtempClient({ host: '127.0.0.1', port, timeoutMs: 1000, name: 'NAS Disks' });
    const snapshot = await client.getSnapshot(true);

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.disks[0].temperature).toEqual(39);

    const runtime = await new HddtempIntegration().setup({ host: '127.0.0.1', port, timeoutMs: 1000, name: 'NAS Disks' }, {});
    const status = await runtime.callService!({ domain: 'hddtemp', service: 'status', target: {} });
    const entities = await runtime.entities();

    expect(status.success).toBeTrue();
    expect((status.data as IHddtempSnapshot).source).toEqual('tcp');
    expect(entities.find((entityArg) => entityArg.id === 'sensor.nas_disks_dev_sdb')?.state).toEqual(41);
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('does not report live refresh success without host, client, snapshot, or raw data', async () => {
  const runtime = await new HddtempIntegration().setup({ name: 'No Source HDD' }, {});
  const refresh = await runtime.callService!({ domain: 'hddtemp', service: 'refresh', target: {} });
  const snapshot = refresh.data as IHddtempSnapshot;

  expect(refresh.success).toBeFalse();
  expect(snapshot.online).toBeFalse();
  expect(snapshot.source).toEqual('runtime');
  expect(snapshot.error).toEqual('HDDTemp snapshots require config.host, an injected client, snapshot, or raw data.');
  expect((await runtime.entities()).length).toEqual(0);
  await runtime.destroy();
});

export default tap.start();
