import { expect, tap } from '@git.zone/tstest/tapbundle';
import { KulerskyClient, KulerskyConfigFlow, KulerskyIntegration, KulerskyMapper, createKulerskyDiscoveryDescriptor, kulerskyProfile, type IKulerskySnapshot, type TKulerskyRawData } from '../../ts/integrations/kulersky/index.js';

const rawData: TKulerskyRawData = {
  device: {
    id: 'kulersky-device-1',
    name: "Kuler Sky Device",
    manufacturer: "Kuler Sky",
    model: "Kuler Sky local integration",
    serialNumber: 'kulersky-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "light", state: true, attributes: { domain: "kulersky" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual Kuler Sky candidates and creates config flow output', async () => {
  const descriptor = createKulerskyDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'kulersky-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'kulersky-device-1', name: "Kuler Sky Device", metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual("kulersky");

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

  const done = await (await new KulerskyConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('kulersky-device-1');
  expect(done.config?.rawData).toEqual(rawData);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("kulersky");
  expect(devices[0].manufacturer).toEqual("Kuler Sky");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "kulersky" && entityArg.platform === "light")).toBeTrue();
});

tap.test('exposes Kuler Sky runtime and unsupported control without executor', async () => {
  const integration = new KulerskyIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(kulerskyProfile.metadata.configFlow).toEqual(true);
  expect(kulerskyProfile.metadata.requirements).toEqual([
    "pykulersky==0.5.8",
  ]);

  const runtime = await integration.setup({ name: "Kuler Sky Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "kulersky", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "kulersky", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IKulerskySnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Kuler Sky Device");

  const command = await runtime.callService!({ domain: "kulersky", service: kulerskyProfile.controlServices?.[0] || '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();
