import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNetgearIntegration, NetgearClient, NetgearConfigFlow, NetgearIntegration, NetgearMapper, createNetgearDiscoveryDescriptor, netgearProfile, type INetgearSnapshot, type TNetgearRawData } from '../../ts/integrations/netgear/index.js';

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

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

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

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

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

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

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

tap.test('exposes NETGEAR runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NetgearIntegration();
  const alias = new HomeAssistantNetgearIntegration();
  expect(alias instanceof NetgearIntegration).toBeTrue();
  expect(alias.domain).toEqual("netgear");
  expect(integration.status).toEqual("control-runtime");
  expect(netgearProfile.metadata.configFlow).toEqual(true);
  expect(netgearProfile.metadata.requirements).toEqual([
    "pynetgear==0.10.10",
  ]);
  expect((netgearProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((itemArg) => itemArg.includes('pynetgear==0.10.10') && itemArg.includes('SOAP'))).toBeTrue();
  expect((netgearProfile.metadata.runtime as { platforms: string[] }).platforms.includes('device_tracker')).toBeTrue();

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

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

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