import { expect, tap } from '@git.zone/tstest/tapbundle';
import { KonnectedClient, KonnectedConfigFlow, KonnectedIntegration, KonnectedMapper, createKonnectedDiscoveryDescriptor, konnectedProfile, type IKonnectedSnapshot, type TKonnectedRawData } from '../../ts/integrations/konnected/index.js';

const rawData: TKonnectedRawData = {
  device: {
    id: 'konnected-device-1',
    name: "Konnected.io (Legacy) Device",
    manufacturer: "Konnected.io (Legacy)",
    model: "Konnected.io (Legacy) local integration",
    serialNumber: 'konnected-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "binary_sensor", state: true, attributes: { domain: "konnected" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

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

tap.test('polls and controls Konnected panels through the documented HTTP API', async () => {
  const originalFetch = globalThis.fetch;
  const calls: Array<{ url: string; init?: RequestInit }> = [];
  globalThis.fetch = (async (inputArg: string | URL | Request, initArg?: RequestInit) => {
    const url = String(inputArg);
    calls.push({ url, init: initArg });
    if (url.endsWith('/status')) {
      return new Response(JSON.stringify({
        mac: '2c:3a:e8:43:8a:38',
        model: 'Konnected Pro',
        swVersion: '2.1.3',
        sensors: [{ zone: '1', state: 1 }],
        actuators: [{ zone: 'out1', state: 0, trigger: 1 }],
        rssi: -31,
      }), { status: 200 });
    }
    if (url.includes('/zone?')) {
      return new Response(JSON.stringify([{ zone: 'out1', state: 0 }]), { status: 200 });
    }
    return new Response(JSON.stringify({ zone: 'out1', state: 1 }), { status: 200 });
  }) as typeof fetch;

  try {
    const client = new KonnectedClient({ host: 'panel.local', port: 17000, name: 'Alarm Panel' });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'switch', service: 'turn_on', target: {}, data: { zone: 'out1' } });
    const toggle = await client.execute({ domain: 'switch', service: 'toggle', target: {}, data: { zone: 'out1' } });

    expect(snapshot.source).toEqual('http');
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'zone_1' && entityArg.state === true)).toBeTrue();
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'actuator_zone_out1' && entityArg.platform === 'switch')).toBeTrue();
    expect(command.success).toBeTrue();
    expect(toggle.success).toBeTrue();
    expect(calls[0].url).toEqual('http://panel.local:17000/status');
    expect(calls[1].url).toEqual('http://panel.local:17000/zone');
    expect(JSON.parse(String(calls[1].init?.body))).toEqual({ zone: 'out1', state: 1 });
    expect(calls[2].url).toEqual('http://panel.local:17000/zone?zone=out1');
    expect(JSON.parse(String(calls[3].init?.body))).toEqual({ zone: 'out1', state: 1 });
  } finally {
    globalThis.fetch = originalFetch;
  }
});

tap.test('exposes Konnected.io (Legacy) runtime and unsupported control without executor', async () => {
  const integration = new KonnectedIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(konnectedProfile.metadata.configFlow).toEqual(true);
  expect(konnectedProfile.metadata.requirements).toEqual([
    "konnected==1.2.0",
  ]);

  const runtime = await integration.setup({ name: "Konnected.io (Legacy) Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "konnected", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "konnected", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IKonnectedSnapshot;

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

  const command = await runtime.callService!({ domain: "konnected", service: konnectedProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires config.host/config.url');
  await runtime.destroy();
});

export default tap.start();
