import { expect, tap } from '@git.zone/tstest/tapbundle';
import { OpenRGBIntegration, type IOpenRGBClientCommand, type IOpenRGBSnapshot } from '../../ts/integrations/openrgb/index.js';

const snapshot: IOpenRGBSnapshot = {
  connected: true,
  name: 'Gaming PC',
  controller: { id: 'gaming-pc', name: 'Gaming PC' },
  devices: [
    {
      id: 0,
      name: 'Mainboard',
      typeName: 'motherboard',
      metadata: { vendor: 'ASRock', description: 'X570 RGB', serial: 'ABC123', location: 'PCI' },
      activeMode: 0,
      modes: [{ id: 0, name: 'Direct', value: 0, flags: 1 << 5, colorMode: 1 }],
      colors: [{ red: 255, green: 255, blue: 255 }],
      leds: [{ id: 0, name: 'LED 1', value: 0 }],
      available: true,
    },
  ],
  profiles: [],
  events: [],
};

tap.test('does not fake OpenRGB SDK command success without host or executor', async () => {
  const runtime = await new OpenRGBIntegration().setup({ snapshot }, {});
  const result = await runtime.callService?.({
    domain: 'light',
    service: 'turn_on',
    target: { entityId: 'light.mainboard' },
    data: { brightness: 100 },
  });
  expect(result?.success).toBeFalse();
  expect(result?.error).toContain('host');
  await runtime.destroy();
});

tap.test('uses commandExecutor for snapshot/manual OpenRGB command execution', async () => {
  let capturedCommand: IOpenRGBClientCommand | undefined;
  const runtime = await new OpenRGBIntegration().setup({
    snapshot,
    commandExecutor: async (commandArg) => {
      capturedCommand = commandArg;
      return { success: true, data: { accepted: true } };
    },
  }, {});
  const result = await runtime.callService?.({
    domain: 'light',
    service: 'turn_on',
    target: { entityId: 'light.mainboard' },
    data: { rgb_color: [255, 0, 0], brightness: 64 },
  });
  const operation = capturedCommand?.operations[0];
  if (operation?.action !== 'setColor') {
    throw new Error('Expected a setColor operation.');
  }
  expect(result?.success).toBeTrue();
  expect(operation.rgb).toEqual({ red: 64, green: 0, blue: 0 });
  await runtime.destroy();
});

export default tap.start();
