import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DropletClient, DropletConfigFlow, DropletIntegration, DropletMapper, HomeAssistantDropletIntegration, createDropletDiscoveryDescriptor, dropletProfile, type IDropletSnapshot } from '../../ts/integrations/droplet/index.js';

const rawData = {
  current_flow_rate: 1.25,
  volume: 30.5,
  server_connectivity: 'connected',
  signal_quality: 'strong_signal',
};

tap.test('matches manual Droplet candidates and creates config flow output', async () => {
  const descriptor = createDropletDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'droplet-manual-match');
  const result = await matcher!.matches({ host: 'droplet.local', name: 'Droplet Kitchen', metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('droplet');

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

  const done = await (await new DropletConfigFlow().start(result.candidate!, {})).submit!({ token: 'PAIR1234' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('droplet.local');
  expect(done.config?.token).toEqual('PAIR1234');
});

tap.test('maps Droplet raw snapshots to runtime devices and entities', async () => {
  const client = new DropletClient({ name: 'Droplet Kitchen', rawData });
  const snapshot = await client.getSnapshot();
  const devices = DropletMapper.toDevices(snapshot);
  const entities = DropletMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('droplet');
  expect(entities.length).toEqual(4);
  expect(entities.some((entityArg) => entityArg.name === 'Signal Quality' && entityArg.state === 'strong_signal')).toBeTrue();
});

tap.test('exposes Droplet read-only runtime, alias, and explicit unsupported control', async () => {
  expect(new HomeAssistantDropletIntegration().domain).toEqual('droplet');
  expect(dropletProfile.status).toEqual('read-only-runtime');
  expect(dropletProfile.metadata.qualityScale).toEqual('bronze');
  expect(dropletProfile.metadata.requirements).toEqual(['pydroplet==2.3.4']);

  const runtime = await new DropletIntegration().setup({ name: 'Droplet Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'droplet', service: 'status', target: {} });
  const snapshot = status.data as IDropletSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Droplet Runtime');

  const controlCommand = await runtime.callService!({ domain: 'droplet', service: 'turn_on', target: {} });
  expect(controlCommand.success).toBeFalse();
  await runtime.destroy();
});

export default tap.start();
