import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FullyKioskClient, FullyKioskIntegration, type IFullyKioskSnapshot } from '../../ts/integrations/fully_kiosk/index.js';

const snapshot: IFullyKioskSnapshot = {
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'snapshot',
  protocol: 'http',
  ssl: false,
  uniqueId: 'device-123',
  name: 'Wall Tablet',
  deviceInfo: {
    deviceID: 'device-123',
    deviceName: 'Wall Tablet',
    deviceManufacturer: 'Samsung',
    deviceModel: 'SM-T500',
    batteryLevel: 87,
    screenOn: true,
  },
  settings: {
    motionDetection: true,
  },
};

tap.test('reads Fully Kiosk snapshots and executes commands over local REST API', async () => {
  const requests: Array<{ cmd: string | null; password: string | null; url?: string | null; key?: string | null; value?: string | null }> = [];
  const server = createServer((requestArg, responseArg) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    const cmd = url.searchParams.get('cmd');
    requests.push({
      cmd,
      password: url.searchParams.get('password'),
      url: url.searchParams.get('url'),
      key: url.searchParams.get('key'),
      value: url.searchParams.get('value'),
    });

    if (url.searchParams.get('password') !== 'secret') {
      responseArg.statusCode = 401;
      responseArg.end('bad password');
      return;
    }
    if (cmd === 'deviceInfo') {
      responseArg.setHeader('content-type', 'application/json');
      responseArg.end(JSON.stringify({
        status: 'OK',
        deviceID: 'device-123',
        deviceName: 'Wall Tablet',
        deviceManufacturer: 'Samsung',
        deviceModel: 'SM-T500',
        appVersionName: '1.60',
        Mac: 'AABBCCDDEEFF',
        ip4: '127.0.0.1',
        batteryLevel: 91,
        screenOn: true,
      }));
      return;
    }
    if (cmd === 'listSettings') {
      responseArg.setHeader('content-type', 'application/json');
      responseArg.end(JSON.stringify({ motionDetection: true, screenBrightness: '100' }));
      return;
    }
    if (cmd === 'getScreenshot') {
      responseArg.setHeader('content-type', 'image/png');
      responseArg.end(Buffer.from([1, 2, 3]));
      return;
    }
    responseArg.setHeader('content-type', 'application/json');
    responseArg.end(JSON.stringify({ status: 'OK', cmd }));
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const client = new FullyKioskClient({ host: '127.0.0.1', port, password: 'secret', timeoutMs: 1000 });
    const liveSnapshot = await client.getSnapshot();

    expect(liveSnapshot.online).toBeTrue();
    expect(liveSnapshot.source).toEqual('http');
    expect(liveSnapshot.deviceInfo.deviceName).toEqual('Wall Tablet');
    expect(liveSnapshot.settings.screenBrightness).toEqual('100');
    expect(requests.some((requestArg) => requestArg.cmd === 'deviceInfo' && requestArg.password === 'secret')).toBeTrue();

    const runtime = await new FullyKioskIntegration().setup({ host: '127.0.0.1', port, password: 'secret', timeoutMs: 1000 }, {});
    const loadResult = await runtime.callService?.({
      domain: 'fully_kiosk',
      service: 'load_url',
      target: {},
      data: { url: 'https://example.test/dashboard' },
    });
    const screenshotResult = await runtime.callService?.({
      domain: 'fully_kiosk',
      service: 'get_screenshot',
      target: {},
    });

    expect(loadResult?.success).toBeTrue();
    expect(screenshotResult?.success).toBeTrue();
    expect((screenshotResult?.data as { dataBase64?: string }).dataBase64).toEqual(Buffer.from([1, 2, 3]).toString('base64'));
    expect(requests.some((requestArg) => requestArg.cmd === 'loadUrl' && requestArg.url === 'https://example.test/dashboard')).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('snapshot services work without claiming live command success', async () => {
  const runtime = await new FullyKioskIntegration().setup({ snapshot }, {});
  const status = await runtime.callService?.({ domain: 'fully_kiosk', service: 'status', target: {} });
  const screenOnEntity = (await runtime.entities()).find((entityArg) => entityArg.attributes?.fullyKioskSwitchKey === 'screen_on');
  const command = await runtime.callService?.({ domain: 'switch', service: 'turn_off', target: { entityId: screenOnEntity?.id } });

  expect(status?.success).toBeTrue();
  expect((status?.data as IFullyKioskSnapshot).deviceInfo.deviceName).toEqual('Wall Tablet');
  expect(command?.success).toBeFalse();
  expect(command?.error).toContain('config.host plus config.password');
  await runtime.destroy();
});

export default tap.start();
