import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantKankunIntegration, KankunClient, KankunConfigFlow, KankunIntegration, KankunMapper, createKankunDiscoveryDescriptor, kankunProfile, type IKankunSnapshot, type TKankunRawData } from '../../ts/integrations/kankun/index.js';

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

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

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

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

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

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

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

tap.test('polls and controls Kankun switches through the documented json.cgi HTTP API', async () => {
  const originalFetch = globalThis.fetch;
  const calls: Array<{ url: string; init?: RequestInit }> = [];
  globalThis.fetch = (async (inputArg: string | URL | Request, initArg?: RequestInit) => {
    const url = String(inputArg);
    calls.push({ url, init: initArg });
    if (url.endsWith('/cgi-bin/json.cgi?get=state')) {
      return new Response(JSON.stringify({ state: 'on' }), { status: 200 });
    }
    if (url.endsWith('/cgi-bin/json.cgi?set=off')) {
      return new Response(JSON.stringify({ ok: true }), { status: 200 });
    }
    return new Response(JSON.stringify({ ok: false }), { status: 404 });
  }) as typeof fetch;

  try {
    const client = new KankunClient({ host: 'plug.local', username: 'admin', password: 'secret', name: 'Bedroom Plug' });
    const snapshot = await client.getSnapshot(true);
    const command = await client.execute({ domain: 'switch', service: 'turn_off', target: {} });

    expect(snapshot.source).toEqual('http');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'switch')?.state).toBeTrue();
    expect(command.success).toBeTrue();
    expect(calls[0].url).toEqual('http://plug.local/cgi-bin/json.cgi?get=state');
    expect(String((calls[0].init?.headers as Record<string, string>).authorization)).toContain('Basic ');
    expect(calls[1].url).toEqual('http://plug.local/cgi-bin/json.cgi?set=off');
  } finally {
    globalThis.fetch = originalFetch;
  }
});

tap.test('exposes Kankun runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new KankunIntegration();
  const alias = new HomeAssistantKankunIntegration();
  expect(alias instanceof KankunIntegration).toBeTrue();
  expect(alias.domain).toEqual("kankun");
  expect(integration.status).toEqual("control-runtime");
  expect(kankunProfile.metadata.configFlow).toEqual(false);
  expect(kankunProfile.metadata.requirements).toEqual([]);

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

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

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