import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LunatoneClient, LunatoneConfigFlow, LunatoneIntegration, LunatoneMapper, createLunatoneDiscoveryDescriptor, lunatoneProfile, type ILunatoneSnapshot, type TLunatoneRawData } from '../../ts/integrations/lunatone/index.js';

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

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

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

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

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

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

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

tap.test('exposes Lunatone runtime and unsupported control without executor', async () => {
  const integration = new LunatoneIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(lunatoneProfile.metadata.configFlow).toEqual(true);
  expect(lunatoneProfile.metadata.requirements).toEqual([
    "lunatone-rest-api-client==0.9.1",
  ]);

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

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

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