import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNx584Integration, Nx584Client, Nx584ConfigFlow, Nx584Integration, Nx584Mapper, createNx584DiscoveryDescriptor, nx584Profile, type INx584Snapshot, type TNx584RawData } from '../../ts/integrations/nx584/index.js';

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

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

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

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

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

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

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

tap.test('reads and controls NX584 through the local pynx584 HTTP bridge', async () => {
  const requests: Array<{ method?: string; url?: string; body: string }> = [];
  const server = createServer((requestArg, responseArg) => {
    const chunks: Buffer[] = [];
    requestArg.on('data', (chunkArg) => chunks.push(Buffer.from(chunkArg)));
    requestArg.on('end', () => {
      const body = Buffer.concat(chunks).toString('utf8');
      requests.push({ method: requestArg.method, url: requestArg.url, body });
      if (requestArg.method === 'GET' && requestArg.url === '/zones') {
        responseArg.setHeader('content-type', 'application/json');
        responseArg.end(JSON.stringify({ zones: [
          { number: 1, name: 'Front Door', state: true, bypassed: false },
          { number: 2, name: 'Hall Motion', state: false, bypassed: true },
        ] }));
        return;
      }
      if (requestArg.method === 'GET' && requestArg.url === '/partitions') {
        responseArg.setHeader('content-type', 'application/json');
        responseArg.end(JSON.stringify({ partitions: [{ number: 1, armed: true, condition_flags: [] }] }));
        return;
      }
      if (requestArg.method === 'GET' && requestArg.url === '/version') {
        responseArg.setHeader('content-type', 'application/json');
        responseArg.end(JSON.stringify({ version: '1.2' }));
        return;
      }
      if (requestArg.method === 'PUT' && requestArg.url === '/zones/2') {
        responseArg.statusCode = body === JSON.stringify({ bypassed: true }) ? 200 : 400;
        responseArg.end('ok');
        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 Nx584Client({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.version).toEqual('1.2');
    expect(snapshot.alarmState).toEqual('armed_home');
    expect(snapshot.zones?.length).toEqual(2);
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'zone_1' && entityArg.state === true)).toBeTrue();

    const commandResult = await client.execute({ domain: 'nx584', service: 'bypass_zone', target: {}, data: { zone: 2 } });
    expect(commandResult.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.method === 'PUT' && requestArg.url === '/zones/2' && requestArg.body === JSON.stringify({ bypassed: true }))).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes NX584 runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new Nx584Integration();
  const alias = new HomeAssistantNx584Integration();
  expect(alias instanceof Nx584Integration).toBeTrue();
  expect(alias.domain).toEqual("nx584");
  expect(integration.status).toEqual("control-runtime");
  expect(nx584Profile.metadata.configFlow).toEqual(false);
  expect(nx584Profile.metadata.requirements).toEqual([
    "pynx584==0.8.2",
  ]);

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

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

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