import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as http from 'node:http';
import type { AddressInfo } from 'node:net';
import { HomeAssistantIsy994Integration, Isy994Client, Isy994ConfigFlow, Isy994Integration, Isy994Mapper, createIsy994DiscoveryDescriptor, isy994Profile, type IIsy994Snapshot, type TIsy994RawData } from '../../ts/integrations/isy994/index.js';

const rawData: TIsy994RawData = {
  device: {
    id: 'isy994-device-1',
    name: "Universal Devices ISY/IoX Device",
    manufacturer: "Universal Devices ISY/IoX",
    model: "Universal Devices ISY/IoX local integration",
    serialNumber: 'isy994-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "binary_sensor", state: true, attributes: { domain: "isy994" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

const listen = async (serverArg: http.Server): Promise<number> => await new Promise((resolveArg) => {
  serverArg.listen(0, '127.0.0.1', () => resolveArg((serverArg.address() as AddressInfo).port));
});

const close = async (serverArg: http.Server): Promise<void> => await new Promise((resolveArg, rejectArg) => {
  serverArg.close((errorArg) => errorArg ? rejectArg(errorArg) : resolveArg());
});

tap.test('matches manual Universal Devices ISY/IoX candidates and creates config flow output', async () => {
  const descriptor = createIsy994DiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'isy994-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'isy994-device-1', name: "Universal Devices ISY/IoX Device", metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual("isy994");

  const validation = await descriptor.getValidators()[0].validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();

  const done = await (await new Isy994ConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('isy994-device-1');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Universal Devices ISY/IoX raw snapshots to runtime devices and entities', async () => {
  const client = new Isy994Client({ name: "Universal Devices ISY/IoX Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = Isy994Mapper.toSnapshotFromRaw({ name: "Universal Devices ISY/IoX Runtime" }, rawData);
  const devices = Isy994Mapper.toDevices(mappedSnapshot);
  const entities = Isy994Mapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("isy994");
  expect(devices[0].manufacturer).toEqual("Universal Devices ISY/IoX");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "isy994" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test('polls Universal Devices ISY/IoX REST XML and sends a native node command', async () => {
  const requests: Array<{ url?: string; authorization?: string }> = [];
  const server = http.createServer((requestArg, responseArg) => {
    requests.push({ url: requestArg.url, authorization: requestArg.headers.authorization });
    responseArg.setHeader('content-type', 'application/xml');
    if (requestArg.url?.startsWith('/rest/config')) {
      responseArg.end('<configuration><root><id>00:21:b9:aa:bb:cc</id><name>Test ISY</name></root><product><desc>ISY994i</desc></product><app_full_version>5.3.4</app_full_version><variables>true</variables><nodedefs>true</nodedefs></configuration>');
      return;
    }
    if (requestArg.url?.startsWith('/rest/nodes/11%2022%2033%201/cmd/DON/255')) {
      responseArg.end('<RestResponse succeeded="true" />');
      return;
    }
    if (requestArg.url?.startsWith('/rest/nodes')) {
      responseArg.end('<nodes><node nodeDefId="DimmerSwitch"><address>11 22 33 1</address><name>Kitchen Light</name><family>1</family><type>1.2.9.0</type><enabled>true</enabled><property id="ST" value="128" formatted="50%" uom="100" prec="0" /></node></nodes>');
      return;
    }
    if (requestArg.url?.startsWith('/rest/status')) {
      responseArg.end('<nodes><node id="11 22 33 1"><property id="ST" value="255" formatted="On" uom="100" prec="0" /></node></nodes>');
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end('not found');
  });
  const port = await listen(server);
  try {
    const client = new Isy994Client({ host: '127.0.0.1', port, username: 'admin', password: 'secret' });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'isy994', service: 'send_raw_node_command', target: {}, data: { address: '11 22 33 1', command: 'DON', value: 255 } });

    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('Test ISY');
    expect(snapshot.entities[0].name).toEqual('Kitchen Light');
    expect(snapshot.entities[0].platform).toEqual('light');
    expect(snapshot.entities[0].state).toEqual(255);
    expect(command.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/rest/nodes/11%2022%2033%201/cmd/DON/255')).toBeTrue();
    expect(requests.every((requestArg) => requestArg.authorization === 'Basic YWRtaW46c2VjcmV0')).toBeTrue();
  } finally {
    await close(server);
  }
});

tap.test('exposes Universal Devices ISY/IoX runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new Isy994Integration();
  const alias = new HomeAssistantIsy994Integration();
  expect(alias instanceof Isy994Integration).toBeTrue();
  expect(alias.domain).toEqual("isy994");
  expect(integration.status).toEqual("control-runtime");
  expect(isy994Profile.metadata.configFlow).toEqual(true);
  expect(isy994Profile.metadata.requirements).toEqual([
    "pyisy==3.5.1",
  ]);

  const runtime = await integration.setup({ name: "Universal Devices ISY/IoX Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "isy994", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "isy994", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IIsy994Snapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Universal Devices ISY/IoX Device");

  const command = await runtime.callService!({ domain: "isy994", service: isy994Profile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
