import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DropConnectClient, DropConnectConfigFlow, DropConnectIntegration, DropConnectMapper, HomeAssistantDropConnectIntegration, createDropConnectDiscoveryDescriptor, dropConnectProfile, type IDropConnectSnapshot } from '../../ts/integrations/drop_connect/index.js';

const rawData = {
  current_flow_rate: 2.1,
  water_used_today: 18,
  leak: false,
  water: true,
  protect_mode: 'home',
};

tap.test('matches manual DROP candidates and creates config flow output', async () => {
  const descriptor = createDropConnectDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'drop_connect-manual-match');
  const result = await matcher!.matches({ name: 'DROP Hub', metadata: { rawData } }, {});

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

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

  const done = await (await new DropConnectConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps DROP raw snapshots to runtime devices and entities', async () => {
  const client = new DropConnectClient({ name: 'DROP Runtime Hub', rawData });
  const snapshot = await client.getSnapshot();
  const devices = DropConnectMapper.toDevices(snapshot);
  const entities = DropConnectMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('drop_connect');
  expect(devices[0].manufacturer).toEqual('Chandler Systems, Inc.');
  expect(entities.some((entityArg) => entityArg.name === 'Current Flow Rate' && entityArg.state === 2.1)).toBeTrue();
});

tap.test('exposes DROP runtime services, alias, and explicit gated control', async () => {
  expect(new HomeAssistantDropConnectIntegration().domain).toEqual('drop_connect');
  expect(dropConnectProfile.status).toEqual('control-runtime');
  expect(dropConnectProfile.metadata.dependencies).toEqual(['mqtt']);
  expect(dropConnectProfile.metadata.requirements).toEqual(['dropmqttapi==1.0.3']);

  const runtime = await new DropConnectIntegration().setup({ name: 'DROP Runtime Hub', rawData }, {});
  const status = await runtime.callService!({ domain: 'drop_connect', service: 'status', target: {} });
  const snapshot = status.data as IDropConnectSnapshot;

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

  const controlCommand = await runtime.callService!({ domain: 'select', service: 'select_option', target: {}, data: { option: 'away' } });
  expect(controlCommand.success).toBeFalse();
  await runtime.destroy();
});

export default tap.start();
