import { expect, tap } from '@git.zone/tstest/tapbundle';
import { WakeOnLanIntegration, type IWakeOnLanCommand } from '../../ts/integrations/wake_on_lan/index.js';

tap.test('does not fake magic packet success without UDP or injected executor', async () => {
  const runtime = await new WakeOnLanIntegration().setup({
    macAddress: 'aa:bb:cc:dd:ee:ff',
    nativeUdpEnabled: false,
  }, {});

  const result = await runtime.callService?.({
    domain: 'wake_on_lan',
    service: 'send_magic_packet',
    target: {},
    data: { mac: 'aa:bb:cc:dd:ee:ff' },
  });

  expect(result?.success).toBeFalse();
  expect(result?.error || '').toInclude('UDP send path is unavailable');
  await runtime.destroy();
});

tap.test('delegates magic packets to an injected executor', async () => {
  let command: IWakeOnLanCommand | undefined;
  const runtime = await new WakeOnLanIntegration().setup({
    macAddress: 'aa:bb:cc:dd:ee:ff',
    name: 'Gaming PC',
    entityTypes: ['button', 'switch'],
    nativeUdpEnabled: false,
    commandExecutor: async (commandArg) => {
      command = commandArg;
      return { success: true, transmitted: true, data: { accepted: true } };
    },
  }, {});

  const result = await runtime.callService?.({
    domain: 'button',
    service: 'press',
    target: { entityId: 'button.gaming_pc_wake' },
    data: {},
  });

  expect(result?.success).toBeTrue();
  expect(command?.type).toEqual('button_press');
  expect(command?.packet?.byteLength).toEqual(102);
  expect(command?.broadcastPort).toEqual(9);
  await runtime.destroy();
});

tap.test('uses native UDP send completion for live success', async () => {
  const runtime = await new WakeOnLanIntegration().setup({
    macAddress: 'aa:bb:cc:dd:ee:ff',
    broadcastAddress: '127.0.0.1',
    broadcastPort: 9,
    udpTimeoutMs: 1000,
  }, {});

  const result = await runtime.callService?.({
    domain: 'wake_on_lan',
    service: 'send_magic_packet',
    target: {},
    data: { mac: 'aa:bb:cc:dd:ee:ff', broadcast_address: '127.0.0.1', broadcast_port: 9 },
  });

  expect(result?.success).toBeTrue();
  expect((result as { transmitted?: boolean } | undefined)?.transmitted).toBeTrue();
  await runtime.destroy();
});

tap.test('requires an injected executor for switch turn_off actions', async () => {
  const runtime = await new WakeOnLanIntegration().setup({
    macAddress: 'aa:bb:cc:dd:ee:ff',
    name: 'Gaming PC',
    entityTypes: ['switch'],
    state: true,
  }, {});

  const result = await runtime.callService?.({
    domain: 'switch',
    service: 'turn_off',
    target: { entityId: 'switch.gaming_pc' },
    data: {},
  });

  expect(result?.success).toBeFalse();
  expect(result?.error || '').toInclude('turn_off actions require an injected commandExecutor');
  await runtime.destroy();
});

export default tap.start();
