import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FivemClient, FivemConfigFlow, FivemIntegration, FivemMapper, HomeAssistantFivemIntegration, createFivemDiscoveryDescriptor, fivemProfile, type IFivemSnapshot, type TFivemRawData } from '../../ts/integrations/fivem/index.js';

const rawData: TFivemRawData = {
  device: {
    id: 'fivem-local',
    name: 'FiveM Local',
    manufacturer: 'Cfx.re',
    model: 'FXServer',
    port: 30120,
  },
  entities: [
    { id: 'status', name: 'Status', platform: 'binary_sensor', state: true, deviceClass: 'connectivity' },
    { id: 'players_online', name: 'Players Online', platform: 'sensor', state: 12, unit: 'players', attributes: { players_list: ['Alice', 'Bob'] } },
    { id: 'players_max', name: 'Players Max', platform: 'sensor', state: 64, unit: 'players' },
    { id: 'resources', name: 'Resources', platform: 'sensor', state: 148, unit: 'resources', attributes: { resources_list: ['mapmanager', 'chat'] } },
  ],
  vars: {
    gamename: 'gta5',
  },
};

tap.test('matches manual FiveM candidates and creates config flow output', async () => {
  const descriptor = createFivemDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'fivem-manual-match');
  const result = await matcher!.matches({ source: 'manual', host: 'fivem.local', port: 30120, name: 'FiveM Server', metadata: { rawData } }, {});

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

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

  const done = await (await new FivemConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('fivem.local');
  expect(done.config?.port).toEqual(30120);
  expect(done.config?.path).toEqual('/dynamic.json');
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('fivem');
  expect(devices[0].manufacturer).toEqual('Cfx.re');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.fivem_local_players_online')).toBeTrue();
});

tap.test('exposes FiveM read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new FivemIntegration();
  const alias = new HomeAssistantFivemIntegration();
  expect(alias instanceof FivemIntegration).toBeTrue();
  expect(alias.domain).toEqual('fivem');
  expect(integration.status).toEqual('read-only-runtime');
  expect(fivemProfile.metadata.configFlow).toEqual(true);
  expect(fivemProfile.metadata.requirements).toEqual(['fivem-api==0.1.2']);

  const runtime = await integration.setup({ name: 'FiveM Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'fivem', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'fivem', service: 'refresh', target: {} });
  const snapshot = status.data as IFivemSnapshot;

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

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