import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNaswebIntegration, NaswebClient, NaswebConfigFlow, NaswebIntegration, NaswebMapper, createNaswebDiscoveryDescriptor, naswebProfile, type INaswebSnapshot, type TNaswebRawData } from '../../ts/integrations/nasweb/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 readBody = async (requestArg: IncomingMessage): Promise<string> => {
  const chunks: Buffer[] = [];
  for await (const chunk of requestArg) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  return Buffer.concat(chunks).toString('utf8');
};

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

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

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

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

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

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

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

tap.test('uses NASweb local REST API and maps push status payloads', async () => {
  const requests: Array<{ method: string; path: string; body: Record<string, unknown> | undefined }> = [];
  const server = createServer(async (requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    const rawBody = await readBody(requestArg);
    const body = rawBody ? JSON.parse(rawBody) as Record<string, unknown> : undefined;
    requests.push({ method: requestArg.method || 'POST', path: url.pathname, body });
    if (url.pathname === '/rest/hello/world') {
      responseArg.statusCode = 200;
      responseArg.setHeader('content-type', 'text/plain');
      responseArg.end('restAPI');
      return;
    }
    if (url.pathname === '/rest/integration/hass/getDeviceInfo') {
      json(responseArg, { devName: 'NASweb Lab', devSN: 'SN-123' });
      return;
    }
    if (url.pathname === '/rest/integration/hass/statusSubscription') {
      json(responseArg, { Answer: 'OK' });
      return;
    }
    if (url.pathname === '/rest/integration/hass/setOutput') {
      json(responseArg, { Answer: 'OK' });
      return;
    }
    json(responseArg, { Answer: 'ERROR' }, 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 statusUpdate = {
      type: 'status_update',
      device_serial: 'SN123',
      outputs: [{ index: 1, status: 'true' }],
      inputs: [{ index: 2, status: 'active' }],
      zones: [{ index: 3, name: 'Garage', status: 'armed', pass_type: 1 }],
      device_temp_env: '23',
      thermostat: { name: 'Thermostat', range_from: '19', range_to: '24', below_check: '1', above_check: '0', idle_output: '4', temp_env: '21' },
    };
    const client = new NaswebClient({ url, useTls: false, username: 'admin', password: 'secret', webhookUrl: 'http://ha.local/api/webhook/nasweb', statusUpdate, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'switch', service: 'turn_off', target: {}, data: { index: 1 } });
    const pushed = client.applyStatusUpdate({ ...statusUpdate, outputs: [{ index: 1, status: 'false' }] });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.device.name).toEqual('NASweb Lab');
    expect(snapshot.device.serialNumber).toEqual('SN123');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'output_1')?.state).toBeTrue();
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'input_2')?.state).toEqual('active');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'temp_sensor')?.state).toEqual(23);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'thermostat')?.state).toEqual('heat');
    expect(command.success).toBeTrue();
    expect(pushed.entities.find((entityArg) => entityArg.id === 'output_1')?.state).toBeFalse();
    expect(requests.some((requestArg) => requestArg.path === '/rest/hello/world')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.path === '/rest/integration/hass/statusSubscription' && requestArg.body?.address === 'http://ha.local/api/webhook/nasweb')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.path === '/rest/integration/hass/setOutput' && requestArg.body?.status === false)).toBeTrue();
    expect(requests.find((requestArg) => requestArg.path === '/rest/integration/hass/getDeviceInfo')?.body?.password).toEqual('E5E9FA1BA31ECD1AE84F75CAAA474F3A663F05F4');
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes NASweb runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NaswebIntegration();
  const alias = new HomeAssistantNaswebIntegration();
  expect(alias instanceof NaswebIntegration).toBeTrue();
  expect(alias.domain).toEqual("nasweb");
  expect(integration.status).toEqual("control-runtime");
  expect(naswebProfile.metadata.configFlow).toEqual(true);
  expect(naswebProfile.metadata.requirements).toEqual([
    "webio-api==0.1.12",
  ]);

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

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

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