import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLutronCasetaIntegration, LutronCasetaClient, LutronCasetaConfigFlow, LutronCasetaIntegration, LutronCasetaMapper, createLutronCasetaDiscoveryDescriptor, lutronCasetaProfile, type ILutronCasetaSnapshot, type TLutronCasetaRawData } from '../../ts/integrations/lutron_caseta/index.js';

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

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

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

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

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

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

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

tap.test('exposes Lutron Caseta runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LutronCasetaIntegration();
  const alias = new HomeAssistantLutronCasetaIntegration();
  expect(alias instanceof LutronCasetaIntegration).toBeTrue();
  expect(alias.domain).toEqual("lutron_caseta");
  expect(integration.status).toEqual("read-only-runtime");
  expect(lutronCasetaProfile.metadata.configFlow).toEqual(true);
  expect(String((lutronCasetaProfile.metadata.localApi as { status?: string }).status)).toContain('pairing-generated');
  expect(lutronCasetaProfile.metadata.requirements).toEqual([
    "pylutron-caseta==0.28.0",
  ]);

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

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

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