import { expect, tap } from '@git.zone/tstest/tapbundle';
import { Gc100Client, Gc100ConfigFlow, Gc100Integration, Gc100Mapper, HomeAssistantGc100Integration, createGc100DiscoveryDescriptor, gc100Profile, type IGc100Snapshot, type TGc100RawData } from '../../ts/integrations/gc100/index.js';

const rawData: TGc100RawData = {
  device: {
    id: 'gc100-1',
    name: 'Global Cache GC-100',
    manufacturer: 'Global Cache',
    model: 'GC-100',
    host: '192.0.2.40',
    port: 4998,
  },
  entities: [
    { id: 'input_1_1', name: 'Input 1:1', platform: 'binary_sensor', state: true, deviceClass: 'opening', attributes: { portAddress: '1:1' } },
    { id: 'relay_1_2', name: 'Relay 1:2', platform: 'switch', state: false, writable: true, attributes: { portAddress: '1:2' } },
  ],
};

tap.test('matches manual GC-100 candidates and creates config flow output', async () => {
  const descriptor = createGc100DiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'gc100-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'gc100-1', name: 'Global Cache GC-100', metadata: { rawData } }, {});

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

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

  const done = await (await new Gc100ConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.name).toEqual('Global Cache GC-100');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps GC-100 raw snapshots to runtime devices and entities', async () => {
  const client = new Gc100Client({ name: 'Global Cache GC-100', rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = Gc100Mapper.toSnapshotFromRaw({ name: 'Global Cache GC-100' }, rawData);
  const devices = Gc100Mapper.toDevices(mappedSnapshot);
  const entities = Gc100Mapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('gc100');
  expect(devices[0].manufacturer).toEqual('Global Cache');
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.global_cache_gc_100_input_1_1')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.global_cache_gc_100_relay_1_2')).toBeTrue();
});

tap.test('exposes GC-100 read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new Gc100Integration();
  const alias = new HomeAssistantGc100Integration();
  expect(alias instanceof Gc100Integration).toBeTrue();
  expect(alias.domain).toEqual('gc100');
  expect(integration.status).toEqual('read-only-runtime');
  expect(gc100Profile.metadata.configFlow).toEqual(false);
  expect(gc100Profile.metadata.qualityScale).toEqual('legacy');
  expect(gc100Profile.metadata.requirements).toEqual(['python-gc100==1.0.3a0']);

  const runtime = await integration.setup({ name: 'Global Cache GC-100', rawData }, {});
  const status = await runtime.callService!({ domain: 'gc100', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'gc100', service: 'refresh', target: {} });
  const snapshot = status.data as IGc100Snapshot;

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Global Cache GC-100');

  const command = await runtime.callService!({ domain: 'switch', service: 'turn_on', target: { entityId: 'switch.global_cache_gc_100_relay_1_2' } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
