import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FortiosClient, FortiosConfigFlow, FortiosIntegration, FortiosMapper, HomeAssistantFortiosIntegration, createFortiosDiscoveryDescriptor, fortiosProfile, type IFortiosSnapshot, type TFortiosRawData } from '../../ts/integrations/fortios/index.js';

const rawData: TFortiosRawData = {
  device: {
    id: 'fortigate-60f',
    name: 'FortiGate 60F',
    manufacturer: 'Fortinet',
    model: 'FortiGate 60F',
    serialNumber: 'FG60FTK000000001',
    host: '192.0.2.10',
  },
  entities: [
    {
      id: 'aa_bb_cc_dd_ee_ff',
      name: 'Laptop',
      platform: 'binary_sensor',
      state: true,
      deviceClass: 'presence',
      attributes: {
        macAddress: 'AA:BB:CC:DD:EE:FF',
        hostname: 'laptop',
      },
    },
    { id: 'firmware_version', name: 'Firmware Version', platform: 'sensor', state: '7.2.8' },
  ],
  clients: [
    { master_mac: 'AA:BB:CC:DD:EE:FF', hostname: 'laptop', is_online: true },
  ],
};

tap.test('matches manual FortiOS candidates and creates config flow output', async () => {
  const descriptor = createFortiosDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'fortios-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'fortigate-60f', name: 'FortiGate 60F', metadata: { rawData } }, {});

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

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

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

tap.test('maps FortiOS raw snapshots to runtime devices and entities', async () => {
  const client = new FortiosClient({ name: 'FortiGate 60F', rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = FortiosMapper.toSnapshotFromRaw({ name: 'FortiGate 60F' }, rawData);
  const devices = FortiosMapper.toDevices(mappedSnapshot);
  const entities = FortiosMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('fortios');
  expect(devices[0].manufacturer).toEqual('Fortinet');
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.fortigate_60f_aa_bb_cc_dd_ee_ff')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'sensor.fortigate_60f_firmware_version')).toBeTrue();
});

tap.test('exposes FortiOS read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new FortiosIntegration();
  const alias = new HomeAssistantFortiosIntegration();
  expect(alias instanceof FortiosIntegration).toBeTrue();
  expect(alias.domain).toEqual('fortios');
  expect(integration.status).toEqual('read-only-runtime');
  expect(fortiosProfile.metadata.configFlow).toEqual(false);
  expect(fortiosProfile.metadata.qualityScale).toEqual('legacy');
  expect(fortiosProfile.metadata.requirements).toEqual(['fortiosapi==1.0.5']);

  const runtime = await integration.setup({ name: 'FortiGate 60F', rawData }, {});
  const status = await runtime.callService!({ domain: 'fortios', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'fortios', service: 'refresh', target: {} });
  const snapshot = status.data as IFortiosSnapshot;

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('FortiGate 60F');

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

export default tap.start();
