import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantModemCalleridIntegration, ModemCalleridClient, ModemCalleridConfigFlow, ModemCalleridIntegration, ModemCalleridMapper, createModemCalleridDiscoveryDescriptor, modemCalleridProfile, type IModemCalleridSnapshot, type TModemCalleridRawData } from '../../ts/integrations/modem_callerid/index.js';

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

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

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

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

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

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

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

tap.test('exposes Phone Modem runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new ModemCalleridIntegration();
  const alias = new HomeAssistantModemCalleridIntegration();
  expect(alias instanceof ModemCalleridIntegration).toBeTrue();
  expect(alias.domain).toEqual("modem_callerid");
  expect(integration.status).toEqual("read-only-runtime");
  expect(modemCalleridProfile.metadata.configFlow).toEqual(true);
  expect(modemCalleridProfile.metadata.requirements).toEqual([
    "phone-modem==0.1.1",
  ]);
  expect(String((modemCalleridProfile.metadata.localApi as Record<string, unknown>).status).includes('serial TTY')).toBeTrue();

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

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

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