import { createServer } from 'node:net';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LocalIpClient, LocalIpConfigFlow, LocalIpIntegration, LocalIpMapper, createLocalIpDiscoveryDescriptor, localIpProfile, type ILocalIpSnapshot, type TLocalIpRawData } from '../../ts/integrations/local_ip/index.js';

const rawData: TLocalIpRawData = {
  device: {
    id: 'local_ip-device-1',
    name: "Local IP Address Device",
    manufacturer: "Local IP Address",
    model: "Local IP Address local integration",
    serialNumber: 'local_ip-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "local_ip" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual Local IP Address candidates and creates config flow output', async () => {
  const descriptor = createLocalIpDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'local_ip-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'local_ip-device-1', name: "Local IP Address Device", metadata: { rawData } }, {});

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

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

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

tap.test('maps Local IP Address raw snapshots to runtime devices and entities', async () => {
  const client = new LocalIpClient({ name: "Local IP Address Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = LocalIpMapper.toSnapshotFromRaw({ name: "Local IP Address Runtime" }, rawData);
  const devices = LocalIpMapper.toDevices(mappedSnapshot);
  const entities = LocalIpMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("local_ip");
  expect(devices[0].manufacturer).toEqual("Local IP Address");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "local_ip" && entityArg.platform === "sensor")).toBeTrue();
});

tap.test('resolves Local IP Address with a local TCP source-address probe', async () => {
  const server = createServer((socketArg) => socketArg.end());
  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 LocalIpClient({ name: 'Route Probe', targetHost: '127.0.0.1', targetPort: port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('tcp');
    expect(snapshot.entities[0].state).toEqual('127.0.0.1');
    expect(snapshot.entities[0].attributes?.targetPort).toEqual(port);

    const runtime = await new LocalIpIntegration().setup({ name: 'Route Probe', targetHost: '127.0.0.1', targetPort: port, timeoutMs: 1000 }, {});
    const status = await runtime.callService!({ domain: 'local_ip', service: 'status', target: {} });
    const runtimeSnapshot = status.data as ILocalIpSnapshot;

    expect(status.success).toBeTrue();
    expect(runtimeSnapshot.entities[0].state).toEqual('127.0.0.1');
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Local IP Address runtime and unsupported control without executor', async () => {
  const integration = new LocalIpIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(localIpProfile.metadata.configFlow).toEqual(true);

  const runtime = await integration.setup({ name: "Local IP Address Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "local_ip", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "local_ip", service: 'refresh', target: {} });
  const snapshot = statusResult.data as ILocalIpSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Local IP Address Device");

  const command = await runtime.callService!({ domain: "local_ip", service: localIpProfile.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();
