import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLinksysSmartIntegration, LinksysSmartClient, LinksysSmartConfigFlow, LinksysSmartIntegration, LinksysSmartMapper, createLinksysSmartDiscoveryDescriptor, linksysSmartProfile, type ILinksysSmartSnapshot, type TLinksysSmartRawData } from '../../ts/integrations/linksys_smart/index.js';

const rawData: TLinksysSmartRawData = {
  device: {
    id: 'linksys_smart-device-1',
    name: "Linksys Smart Wi-Fi Device",
    manufacturer: "Linksys Smart Wi-Fi",
    model: "Linksys Smart Wi-Fi local integration",
    serialNumber: 'linksys_smart-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "linksys_smart" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

tap.test('maps Linksys Smart Wi-Fi raw snapshots to runtime devices and entities', async () => {
  const client = new LinksysSmartClient({ name: "Linksys Smart Wi-Fi Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = LinksysSmartMapper.toSnapshotFromRaw({ name: "Linksys Smart Wi-Fi Runtime" }, rawData);
  const devices = LinksysSmartMapper.toDevices(mappedSnapshot);
  const entities = LinksysSmartMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("linksys_smart");
  expect(devices[0].manufacturer).toEqual("Linksys Smart Wi-Fi");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "linksys_smart" && entityArg.platform === "sensor")).toBeTrue();
});

tap.test('fetches Linksys Smart Wi-Fi JNAP connected device snapshots', async () => {
  const calls: Array<{ url?: string; method?: string; action?: string; body: unknown }> = [];
  const server = createServer(async (requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const body = await readJsonBody(requestArg);
    calls.push({ url: requestArg.url, method: requestArg.method, action: requestArg.headers['x-jnap-action'] as string | undefined, body });
    if (requestArg.method !== 'POST' || requestArg.url !== '/JNAP/') {
      responseArg.statusCode = 404;
      responseArg.end('not found');
      return;
    }
    responseArg.statusCode = 200;
    responseArg.setHeader('content-type', 'application/json');
    responseArg.end(JSON.stringify({
      responses: [{
        output: {
          devices: [
            {
              deviceID: 'device-1',
              friendlyName: 'Laptop fallback',
              knownMACAddresses: ['AA:BB:CC:DD:EE:01'],
              connections: [{ ipAddress: '192.168.1.10' }],
              properties: [{ name: 'userDeviceName', value: 'Laptop' }],
            },
            {
              deviceID: 'device-2',
              friendlyName: 'Phone',
              knownMACAddresses: ['AA:BB:CC:DD:EE:02'],
              connections: [],
              properties: [],
            },
            {
              deviceID: 'device-3',
              friendlyName: 'No MAC',
              knownMACAddresses: [],
              connections: [{ ipAddress: '192.168.1.11' }],
              properties: [],
            },
            {
              deviceID: 'device-4',
              friendlyName: 'Printer',
              knownMACAddresses: ['AA:BB:CC:DD:EE:03'],
              connections: [{ ipAddress: '192.168.1.12' }],
              properties: [],
            },
          ],
        },
      }],
    }));
  });
  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  const address = server.address();
  const port = typeof address === 'object' && address ? address.port : 0;

  try {
    const config = { host: '127.0.0.1', port, timeoutMs: 1000, name: 'Linksys Router' };
    const client = new LinksysSmartClient(config);
    const snapshot = await client.getSnapshot(true);
    const runtime = await new LinksysSmartIntegration().setup(config, {});
    const entities = await runtime.entities();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'connected_devices')?.state).toEqual(2);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'presence_aa_bb_cc_dd_ee_01')?.name).toEqual('Laptop');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'presence_aa_bb_cc_dd_ee_03')?.name).toEqual('Printer');
    expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.linksys_router_presence_aa_bb_cc_dd_ee_01')).toBeTrue();
    expect(calls[0].action).toEqual('http://linksys.com/jnap/core/Transaction');
    expect(calls[0].body).toEqual([{ request: { sinceRevision: 0 }, action: 'http://linksys.com/jnap/devicelist/GetDevices' }]);
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Linksys Smart Wi-Fi runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LinksysSmartIntegration();
  const alias = new HomeAssistantLinksysSmartIntegration();
  expect(alias instanceof LinksysSmartIntegration).toBeTrue();
  expect(alias.domain).toEqual("linksys_smart");
  expect(integration.status).toEqual("read-only-runtime");
  expect(linksysSmartProfile.metadata.configFlow).toEqual(false);
  expect(linksysSmartProfile.metadata.requirements).toEqual([]);

  const runtime = await integration.setup({ name: "Linksys Smart Wi-Fi Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "linksys_smart", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "linksys_smart", service: 'refresh', target: {} });
  const snapshot = statusResult.data as ILinksysSmartSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Linksys Smart Wi-Fi Device");

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

const readJsonBody = async (requestArg: IncomingMessage): Promise<unknown> => {
  const chunks: Buffer[] = [];
  for await (const chunk of requestArg) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  const text = Buffer.concat(chunks).toString('utf8');
  return text ? JSON.parse(text) as unknown : undefined;
};
