import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNamIntegration, NamClient, NamConfigFlow, NamIntegration, NamMapper, createNamDiscoveryDescriptor, namProfile, type INamSnapshot, type TNamRawData } from '../../ts/integrations/nam/index.js';

const json = (responseArg: ServerResponse, valueArg: unknown, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'application/json');
  responseArg.end(JSON.stringify(valueArg));
};

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("nam");
  expect(devices[0].manufacturer).toEqual("Nettigo Air Monitor");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "nam" && entityArg.platform === "button")).toBeTrue();
});

tap.test('reads Nettigo Air Monitor local HTTP data and posts restart', async () => {
  const requests: Array<{ method: string; path: string; authorization?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    requests.push({ method: requestArg.method || 'GET', path: url.pathname, authorization: requestArg.headers.authorization });
    if (url.pathname === '/config') {
      responseArg.statusCode = 200;
      responseArg.setHeader('content-type', 'text/plain');
      responseArg.end('NAM config AA:BB:CC:DD:EE:FF');
      return;
    }
    if (url.pathname === '/data.json') {
      json(responseArg, {
        software_version: 'NAMF-2026.1',
        uptime: 123,
        sensordatavalues: [
          { value_type: 'temperature', value: '21.5' },
          { value_type: 'humidity', value: '45.1' },
          { value_type: 'bme280_pressure', value: '101325' },
          { value_type: 'sds_p1', value: '12' },
          { value_type: 'signal', value: '-61' },
        ],
      });
      return;
    }
    if (url.pathname === '/reset') {
      responseArg.statusCode = 200;
      responseArg.end('OK');
      return;
    }
    json(responseArg, { error: 'not_found' }, 404);
  });

  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 url = `http://127.0.0.1:${port}`;
    const client = new NamClient({ url, username: 'user', password: 'pass', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'button', service: 'press', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('aabbccddeeff');
    expect(snapshot.device.attributes?.softwareVersion).toEqual('NAMF-2026.1');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'dht22_temperature')?.state).toEqual(21.5);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'bme280_pressure')?.state).toEqual(1013.25);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'sds011_p1')?.state).toEqual(12);
    expect(command.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.path === '/config')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.method === 'POST' && requestArg.path === '/reset')).toBeTrue();
    expect(requests[0].authorization).toContain('Basic ');
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Nettigo Air Monitor runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NamIntegration();
  const alias = new HomeAssistantNamIntegration();
  expect(alias instanceof NamIntegration).toBeTrue();
  expect(alias.domain).toEqual("nam");
  expect(integration.status).toEqual("control-runtime");
  expect(namProfile.metadata.configFlow).toEqual(true);
  expect(namProfile.metadata.requirements).toEqual([
    "nettigo-air-monitor==5.0.0",
  ]);

  const runtime = await integration.setup({ name: "Nettigo Air Monitor Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "nam", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "nam", service: 'refresh', target: {} });
  const snapshot = statusResult.data as INamSnapshot;

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

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