import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOralbIntegration, OralbClient, OralbConfigFlow, OralbIntegration, OralbMapper, createOralbDiscoveryDescriptor, oralbProfile, type IOralbSnapshot, type TOralbRawData } from '../../ts/integrations/oralb/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("oralb");
  expect(devices[0].manufacturer).toEqual("Oral-B");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "oralb" && entityArg.platform === "sensor")).toBeTrue();
});

tap.test('exposes Oral-B runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OralbIntegration();
  const alias = new HomeAssistantOralbIntegration();
  expect(alias instanceof OralbIntegration).toBeTrue();
  expect(alias.domain).toEqual("oralb");
  expect(integration.status).toEqual("read-only-runtime");
  expect(oralbProfile.metadata.configFlow).toEqual(true);
  expect(oralbProfile.metadata.requirements).toEqual([
    "oralb-ble==1.1.0",
  ]);
  const localApi = oralbProfile.metadata.localApi as { status: string; explicitUnsupported: string[] };
  const runtimeMetadata = oralbProfile.metadata.runtime as { blocker: string };
  expect(localApi.status).toEqual('blocked-ble-only');
  expect(runtimeMetadata.blocker).toContain('ActiveBluetoothProcessorCoordinator');
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('BluetoothServiceInfoBleak') && itemArg.includes('HTTP/TCP/TLS/file'))).toBeTrue();
  expect(localApi.explicitUnsupported.some((itemArg) => itemArg.includes('BLE') && itemArg.includes('TypeScript BLE dependency'))).toBeTrue();

  const runtime = await integration.setup({ name: "Oral-B Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "oralb", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "oralb", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IOralbSnapshot;

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

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