import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMobileAppIntegration, MobileAppClient, MobileAppConfigFlow, MobileAppIntegration, MobileAppMapper, createMobileAppDiscoveryDescriptor, mobileAppProfile, type IMobileAppSensorState, type IMobileAppSnapshot, type TMobileAppRawData } from '../../ts/integrations/mobile_app/index.js';

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

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

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

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

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

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

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

tap.test('registers Mobile App over Home Assistant HTTP and posts webhook sensor updates', async () => {
  const originalFetch = globalThis.fetch;
  const calls: Array<{ url: string; method?: string; authorization?: string; body?: string }> = [];
  globalThis.fetch = (async (urlArg: URL | RequestInfo, initArg?: RequestInit) => {
    calls.push({
      url: String(urlArg),
      method: initArg?.method,
      authorization: (initArg?.headers as Record<string, string> | undefined)?.authorization,
      body: initArg?.body as string | undefined,
    });
    const path = new URL(String(urlArg)).pathname;
    if (path === '/api/mobile_app/registrations') {
      return new Response(JSON.stringify({ webhook_id: 'webhook-123', remote_ui_url: null, cloudhook_url: null }), { status: 201, headers: { 'content-type': 'application/json' } });
    }
    if (path === '/api/webhook/webhook-123') {
      return new Response(JSON.stringify({ battery_level: { success: true } }), { status: 200, headers: { 'content-type': 'application/json' } });
    }
    return new Response('{}', { status: 404, headers: { 'content-type': 'application/json' } });
  }) as typeof globalThis.fetch;

  try {
    const client = new MobileAppClient({
      url: 'http://127.0.0.1:8123',
      token: 'ha-token',
      deviceId: 'device-abc',
      deviceName: 'TypeScript Phone',
      appId: 'smarthome_exchange_test',
      appName: 'smarthome.exchange Test',
      appVersion: '1.0.0',
      manufacturer: 'smarthome.exchange',
      model: 'Test Client',
      osName: 'Node.js',
      osVersion: 'v25.0.0',
      supportsEncryption: false,
    });
    const snapshot = await client.getSnapshot();
    const sensor: IMobileAppSensorState = { type: 'sensor', unique_id: 'battery_level', name: 'Battery Level', state: 87, unit_of_measurement: '%' };
    const updateResult = await client.updateSensorStates([sensor]) as Record<string, { success: boolean }>;
    const registrationPayload = JSON.parse(calls[0].body || '{}');
    const webhookPayload = JSON.parse(calls[1].body || '{}');

    expect(snapshot.online).toBeTrue();
    expect(snapshot.device.id).toEqual('device-abc');
    expect(calls[0].url).toEqual('http://127.0.0.1:8123/api/mobile_app/registrations');
    expect(calls[0].authorization).toEqual('Bearer ha-token');
    expect(registrationPayload.supports_encryption).toBeFalse();
    expect(registrationPayload.device_name).toEqual('TypeScript Phone');
    expect(calls[1].url).toEqual('http://127.0.0.1:8123/api/webhook/webhook-123');
    expect(webhookPayload.type).toEqual('update_sensor_states');
    expect(webhookPayload.data[0].unique_id).toEqual('battery_level');
    expect(updateResult.battery_level.success).toBeTrue();
  } finally {
    globalThis.fetch = originalFetch;
  }
});

tap.test('exposes Mobile App runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MobileAppIntegration();
  const alias = new HomeAssistantMobileAppIntegration();
  expect(alias instanceof MobileAppIntegration).toBeTrue();
  expect(alias.domain).toEqual("mobile_app");
  expect(integration.status).toEqual("read-only-runtime");
  expect(mobileAppProfile.metadata.configFlow).toEqual(true);
  expect(mobileAppProfile.metadata.requirements).toEqual([
    "PyNaCl==1.6.2",
  ]);

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

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

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