import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOrviboIntegration, OrviboClient, OrviboConfigFlow, OrviboIntegration, OrviboMapper, createOrviboDiscoveryDescriptor, orviboProfile, type IOrviboSnapshot, type TOrviboRawData } from '../../ts/integrations/orvibo/index.js';

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

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

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

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

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

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

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

tap.test('exposes Orvibo runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OrviboIntegration();
  const alias = new HomeAssistantOrviboIntegration();
  expect(alias instanceof OrviboIntegration).toBeTrue();
  expect(alias.domain).toEqual("orvibo");
  expect(integration.status).toEqual("control-runtime");
  expect(orviboProfile.metadata.configFlow).toEqual(true);
  expect(orviboProfile.metadata.requirements).toEqual([
    "orvibo==1.1.2",
  ]);

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

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

  const command = await runtime.callService!({ domain: "orvibo", service: orviboProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('UDP-only binary protocol');
  expect((orviboProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((itemArg) => itemArg.includes('UDP-only binary protocol'))).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
