import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNetgearLteIntegration, NetgearLteClient, NetgearLteConfigFlow, NetgearLteIntegration, NetgearLteMapper, createNetgearLteDiscoveryDescriptor, netgearLteProfile, type INetgearLteSnapshot, type TNetgearLteRawData } from '../../ts/integrations/netgear_lte/index.js';

const rawData: TNetgearLteRawData = {
  device: {
    id: 'netgear_lte-device-1',
    name: "NETGEAR LTE Device",
    manufacturer: "NETGEAR LTE",
    model: "NETGEAR LTE local integration",
    serialNumber: 'netgear_lte-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "binary_sensor", state: true, attributes: { domain: "netgear_lte" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("netgear_lte");
  expect(devices[0].manufacturer).toEqual("NETGEAR LTE");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "netgear_lte" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test('polls and controls NETGEAR LTE over local HTTP', async () => {
  const forms: URLSearchParams[] = [];
  const modelData = {
    general: { FSN: 'NETGEAR123', deviceName: 'LB2120', model: 'LB2120' },
    session: { secToken: 'token-1' },
    wwan: {
      dataUsage: { generic: { dataTransferred: 12345 } },
      connection: 'Connected',
      connectionText: 'Connected',
      connectionType: 'LTE',
      currentNWserviceType: 'LTE',
      currentPSserviceType: 'LTE',
      registerNetworkDisplay: 'Carrier',
      roaming: false,
    },
    wwanadv: { radioQuality: 80, rxLevel: -67, txLevel: -10, curBand: 'B3', cellId: '123456' },
    failover: { backhaul: 'LTE', wanConnected: true },
    sms: { msgs: [{ id: '7', rxTime: '11/03/18 08:18:11 PM', text: 'hello', sender: '5551234', read: false }] },
  };
  const server = createServer((requestArg, responseArg) => {
    if (requestArg.method === 'GET' && requestArg.url === '/model.json') {
      responseArg.setHeader('content-type', 'application/json');
      responseArg.end(JSON.stringify(modelData));
      return;
    }
    if (requestArg.method === 'POST' && requestArg.url === '/Forms/config') {
      const chunks: Buffer[] = [];
      requestArg.on('data', (chunkArg) => chunks.push(Buffer.isBuffer(chunkArg) ? chunkArg : Buffer.from(chunkArg)));
      requestArg.on('end', () => {
        forms.push(new URLSearchParams(Buffer.concat(chunks).toString('utf8')));
        responseArg.setHeader('set-cookie', 'Session=abc; Path=/');
        responseArg.end('{"ok":true}');
      });
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end('not found');
  });

  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 NetgearLteClient({ host: '127.0.0.1', port, password: 'secret', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('NETGEAR123');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'usage')?.state).toEqual(12345);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'mobile_connected')?.state).toBeTrue();
    expect(forms[0].get('session.password')).toEqual('secret');

    const result = await client.execute({ domain: 'netgear_lte', service: 'disconnect_lte', target: {}, data: {} });
    expect(result.success).toBeTrue();
    expect(forms.some((formArg) => formArg.get('wwan.connect') === 'Disconnect' && formArg.get('token') === 'token-1')).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes NETGEAR LTE runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NetgearLteIntegration();
  const alias = new HomeAssistantNetgearLteIntegration();
  expect(alias instanceof NetgearLteIntegration).toBeTrue();
  expect(alias.domain).toEqual("netgear_lte");
  expect(integration.status).toEqual("control-runtime");
  expect(netgearLteProfile.metadata.configFlow).toEqual(true);
  expect(netgearLteProfile.metadata.requirements).toEqual([
    "eternalegypt==0.0.18",
  ]);

  const runtime = await integration.setup({ name: "NETGEAR LTE Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "netgear_lte", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "netgear_lte", service: 'refresh', target: {} });
  const snapshot = statusResult.data as INetgearLteSnapshot;

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

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