import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLocativeIntegration, LocativeClient, LocativeConfigFlow, LocativeIntegration, LocativeMapper, createLocativeDiscoveryDescriptor, locativeProfile, type ILocativeSnapshot, type TLocativeRawData } from '../../ts/integrations/locative/index.js';

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

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

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

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

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

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

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

tap.test('exposes Locative runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LocativeIntegration();
  const alias = new HomeAssistantLocativeIntegration();
  expect(alias instanceof LocativeIntegration).toBeTrue();
  expect(alias.domain).toEqual("locative");
  expect(integration.status).toEqual("read-only-runtime");
  expect(locativeProfile.metadata.configFlow).toEqual(true);
  expect(locativeProfile.metadata.requirements).toEqual([]);
  expect(JSON.stringify(locativeProfile.metadata.runtime)).toContain('device_tracker');
  expect(JSON.stringify(locativeProfile.metadata.localApi)).toContain('inbound webhook receiver');

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

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

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