import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMotionBlindsIntegration, MotionBlindsClient, MotionBlindsConfigFlow, MotionBlindsIntegration, MotionBlindsMapper, createMotionBlindsDiscoveryDescriptor, motionBlindsProfile, type IMotionBlindsSnapshot, type TMotionBlindsRawData } from '../../ts/integrations/motion_blinds/index.js';

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

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

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

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

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

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

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

tap.test('exposes Motionblinds runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MotionBlindsIntegration();
  const alias = new HomeAssistantMotionBlindsIntegration();
  expect(alias instanceof MotionBlindsIntegration).toBeTrue();
  expect(alias.domain).toEqual("motion_blinds");
  expect(integration.status).toEqual("control-runtime");
  expect(motionBlindsProfile.metadata.configFlow).toEqual(true);
  expect(motionBlindsProfile.metadata.requirements).toEqual([
    "motionblinds==0.6.30",
  ]);
  expect((motionBlindsProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((entryArg) => entryArg.includes('UDP port 32100'))).toBeTrue();

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

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

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