import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNrgkickIntegration, NrgkickClient, NrgkickConfigFlow, NrgkickIntegration, NrgkickMapper, createNrgkickDiscoveryDescriptor, nrgkickProfile, type INrgkickSnapshot, type TNrgkickRawData } from '../../ts/integrations/nrgkick/index.js';

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

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

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

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

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

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

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

tap.test('exposes NRGkick runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NrgkickIntegration();
  const alias = new HomeAssistantNrgkickIntegration();
  expect(alias instanceof NrgkickIntegration).toBeTrue();
  expect(alias.domain).toEqual("nrgkick");
  expect(integration.status).toEqual("control-runtime");
  expect(nrgkickProfile.metadata.configFlow).toEqual(true);
  expect(nrgkickProfile.metadata.requirements).toEqual([
    "nrgkick-api==1.7.1",
  ]);

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

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

  const command = await runtime.callService!({ domain: "nrgkick", service: nrgkickProfile.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 NRGkick over the native local JSON API', async () => {
  const requests: Array<{ url?: string; authorization?: string }> = [];
  const server = createServer((requestArg, responseArg) => {
    requests.push({ url: requestArg.url, authorization: requestArg.headers.authorization });
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    responseArg.setHeader('content-type', 'application/json');
    if (url.pathname === '/info') {
      responseArg.end(JSON.stringify({
        general: { device_name: 'Garage NRGkick', serial_number: 'NRG123', model_type: 'NRGkick Gen2', rated_current: 32 },
        connector: { max_current: 16, phase_count: 3, type: 1 },
        network: { mac_address: 'AA:BB:CC:DD:EE:FF', ssid: 'garage', rssi: -55 },
        versions: { sw_sm: '4.2.0', hw_sm: '2' },
      }));
      return;
    }
    if (url.pathname === '/values') {
      responseArg.end(JSON.stringify({
        general: { status: 3, charge_permitted: 1 },
        energy: { total_charged_energy: 123456, charged_energy: 4567 },
        powerflow: { charging_current: 12, total_active_power: 8123 },
      }));
      return;
    }
    if (url.pathname === '/control') {
      if (url.searchParams.has('current_set')) {
        responseArg.end(JSON.stringify({ current_set: Number(url.searchParams.get('current_set')) }));
        return;
      }
      if (url.searchParams.has('charge_pause')) {
        responseArg.end(JSON.stringify({ charge_pause: Number(url.searchParams.get('charge_pause')) }));
        return;
      }
      responseArg.end(JSON.stringify({ current_set: 10, charge_pause: 0, energy_limit: 0, phase_count: 3 }));
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end(JSON.stringify({ Response: '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 NrgkickClient({ host: '127.0.0.1', port, username: 'api', password: 'secret', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const setCurrent = await client.execute({ domain: 'number', service: 'set_value', target: { entityId: 'number.garage_nrgkick_current_set' }, data: { value: 16 } });
    const pause = await client.execute({ domain: 'switch', service: 'turn_off', target: { entityId: 'switch.garage_nrgkick_charging_enabled' }, data: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('NRG123');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'status')?.state).toEqual('charging');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'total_active_power')?.state).toEqual(8123);
    expect(setCurrent.success).toBeTrue();
    expect(pause.success).toBeTrue();
    expect(requests[0].authorization).toEqual(`Basic ${Buffer.from('api:secret').toString('base64')}`);
    expect(requests.some((requestArg) => requestArg.url === '/info?raw=1')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/values?raw=1')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/control?current_set=16')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/control?charge_pause=1')).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

export default tap.start();
