import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ImmichClient, ImmichConfigFlow, ImmichIntegration, ImmichMapper, createImmichDiscoveryDescriptor, immichProfile, type IImmichSnapshot, type TImmichRawData } from '../../ts/integrations/immich/index.js';

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

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

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

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

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

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

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

tap.test('exposes Immich runtime and unsupported control without executor', async () => {
  const integration = new ImmichIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(immichProfile.metadata.configFlow).toEqual(true);
  expect(immichProfile.metadata.requirements).toEqual([
    "aioimmich==0.14.0",
  ]);

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

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

  const command = await runtime.callService!({ domain: "immich", service: immichProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('upload_file requires config.url or config.host plus config.apiKey/config.token');
  await runtime.destroy();
});

export default tap.start();
