import { expect, tap } from '@git.zone/tstest/tapbundle';
import { MealieClient, MealieConfigFlow, MealieIntegration, MealieMapper, createMealieDiscoveryDescriptor, mealieProfile, type IMealieSnapshot, type TMealieRawData } from '../../ts/integrations/mealie/index.js';

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

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

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

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

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

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

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

tap.test('exposes Mealie runtime and unsupported control without executor', async () => {
  const integration = new MealieIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(mealieProfile.metadata.configFlow).toEqual(true);
  expect(mealieProfile.metadata.requirements).toEqual([
    "aiomealie==1.2.4",
  ]);

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

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeFalse();
  expect(refresh.error!).toContain('Mealie refresh requires a live HTTP endpoint');
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Mealie Device");

  const command = await runtime.callService!({ domain: "mealie", service: mealieProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('Mealie commands require config.host/config.url with token/apiToken');
  await runtime.destroy();
});

export default tap.start();
