import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNukiIntegration, NukiClient, NukiConfigFlow, NukiIntegration, NukiMapper, createNukiDiscoveryDescriptor, nukiProfile, type INukiSnapshot, type TNukiRawData } from '../../ts/integrations/nuki/index.js';

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

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

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

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

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

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

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

tap.test('exposes Nuki Bridge runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NukiIntegration();
  const alias = new HomeAssistantNukiIntegration();
  expect(alias instanceof NukiIntegration).toBeTrue();
  expect(alias.domain).toEqual("nuki");
  expect(integration.status).toEqual("control-runtime");
  expect(nukiProfile.metadata.configFlow).toEqual(true);
  expect(nukiProfile.metadata.requirements).toEqual([
    "pynuki==1.6.3",
  ]);

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

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

  const command = await runtime.callService!({ domain: "nuki", service: nukiProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

tap.test('reads and writes Nuki Bridge over the native local HTTP API', async () => {
  const requests: string[] = [];
  const server = createServer((requestArg, responseArg) => {
    requests.push(requestArg.url || '');
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    expect(url.searchParams.get('token')).toEqual('plain-token');
    responseArg.setHeader('content-type', 'application/json');
    if (url.pathname === '/info') {
      responseArg.end(JSON.stringify({
        bridgeType: 1,
        ids: { hardwareId: 305419896 },
        versions: { firmwareVersion: '1.23.4', wifiFirmwareVersion: '2.0.0' },
      }));
      return;
    }
    if (url.pathname === '/list') {
      responseArg.end(JSON.stringify([
        {
          nukiId: 123456,
          name: 'Front Door',
          deviceType: 0,
          firmwareVersion: '3.7.0',
          lastKnownState: { state: 1, stateName: 'locked', batteryCritical: false, batteryCharging: false, batteryChargeState: 87, doorsensorState: 2, doorsensorStateName: 'closed' },
        },
      ]));
      return;
    }
    if (url.pathname === '/lockAction') {
      expect(url.searchParams.get('nukiId')).toEqual('123456');
      expect(url.searchParams.get('deviceType')).toEqual('0');
      expect(url.searchParams.get('action')).toEqual('4');
      responseArg.end(JSON.stringify({ success: true }));
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end(JSON.stringify({ success: false }));
  });

  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 NukiClient({ host: '127.0.0.1', port, token: 'plain-token', encryptToken: false, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const lockNGo = await client.execute({ domain: 'nuki', service: 'lock_n_go', target: {}, data: { nukiId: 123456 } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('12345678');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'device_123456')?.state).toBeFalse();
    expect(snapshot.entities.find((entityArg) => entityArg.id === '123456_battery_level')?.state).toEqual(87);
    expect(lockNGo.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.startsWith('/info?'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.startsWith('/list?'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.startsWith('/lockAction?'))).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('does not fake encrypted Nuki token support without libsodium', async () => {
  const client = new NukiClient({ host: '127.0.0.1', token: 'secret', encryptToken: true, timeoutMs: 100 });
  const snapshot = await client.getSnapshot(true);

  expect(snapshot.online).toBeFalse();
  expect(snapshot.error!).toContain('Encrypted Nuki ctoken/nonce authentication requires PyNaCl/libsodium');
});

export default tap.start();
