import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOpengarageIntegration, OpengarageClient, OpengarageConfigFlow, OpengarageIntegration, OpengarageMapper, createOpengarageDiscoveryDescriptor, opengarageProfile, type IOpengarageSnapshot, type TOpengarageRawData } from '../../ts/integrations/opengarage/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: TOpengarageRawData = {
  device: {
    id: 'opengarage-device-1',
    name: "OpenGarage Device",
    manufacturer: "OpenGarage",
    model: "OpenGarage local integration",
    serialNumber: 'opengarage-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "binary_sensor", state: true, attributes: { domain: "opengarage" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

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

tap.test('polls OpenGarage /jc over native HTTP and sends /cc cover command', async () => {
  const requests: Array<{ path: string; dkey?: string; click?: string; reboot?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    requests.push({
      path: url.pathname,
      dkey: url.searchParams.get('dkey') || undefined,
      click: url.searchParams.get('click') || undefined,
      reboot: url.searchParams.get('reboot') || undefined,
    });

    if (url.pathname === '/jc') {
      json(responseArg, {
        name: 'Garage Controller',
        mac: 'AA:BB:CC:DD:EE:FF',
        fwv: '1.2.3',
        door: 1,
        vehicle: 0,
        dist: 42,
        rssi: -60,
        temp: 21.5,
        humid: 55,
      });
      return;
    }
    if (url.pathname === '/cc' && url.searchParams.get('dkey') === 'secret' && url.searchParams.get('click') === '1') {
      json(responseArg, { result: 1 });
      return;
    }

    json(responseArg, { result: 2 }, url.pathname === '/cc' ? 200 : 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 OpengarageClient({ url, deviceKey: 'secret', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const runtime = await new OpengarageIntegration().setup({ url, deviceKey: 'secret', timeoutMs: 1000 }, {});
    const entities = await runtime.entities();
    const cover = entities.find((entityArg) => entityArg.platform === 'cover')!;
    const command = await runtime.callService!({ domain: 'cover', service: 'close_cover', target: { entityId: cover.id } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('Garage Controller');
    expect(snapshot.device.serialNumber).toEqual('AA:BB:CC:DD:EE:FF');
    expect(cover.state).toEqual('open');
    expect(entities.find((entityArg) => entityArg.name === 'Distance')?.state).toEqual(42);
    expect(command.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.path === '/jc')).toBeTrue();
    expect(requests.find((requestArg) => requestArg.path === '/cc')?.dkey).toEqual('secret');
    expect(requests.find((requestArg) => requestArg.path === '/cc')?.click).toEqual('1');
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes OpenGarage runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OpengarageIntegration();
  const alias = new HomeAssistantOpengarageIntegration();
  expect(alias instanceof OpengarageIntegration).toBeTrue();
  expect(alias.domain).toEqual("opengarage");
  expect(integration.status).toEqual("control-runtime");
  expect(opengarageProfile.metadata.configFlow).toEqual(true);
  expect(opengarageProfile.metadata.requirements).toEqual([
    "open-garage==0.2.0",
  ]);
  expect(opengarageProfile.defaultHttpPath).toEqual('/jc');

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

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

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