import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNfandroidtvIntegration, NfandroidtvClient, NfandroidtvConfigFlow, NfandroidtvIntegration, NfandroidtvMapper, createNfandroidtvDiscoveryDescriptor, nfandroidtvProfile, type INfandroidtvSnapshot, type TNfandroidtvRawData } from '../../ts/integrations/nfandroidtv/index.js';

const rawData: TNfandroidtvRawData = {
  device: {
    id: 'nfandroidtv-device-1',
    name: "Notifications for Android TV / Fire TV Device",
    manufacturer: "Notifications for Android TV / Fire TV",
    model: "Notifications for Android TV / Fire TV local integration",
    serialNumber: 'nfandroidtv-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "nfandroidtv" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual Notifications for Android TV / Fire TV candidates and creates config flow output', async () => {
  const descriptor = createNfandroidtvDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'nfandroidtv-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'nfandroidtv-device-1', name: "Notifications for Android TV / Fire TV Device", metadata: { rawData } }, {});

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

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

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

tap.test('maps Notifications for Android TV / Fire TV raw snapshots to runtime devices and entities', async () => {
  const client = new NfandroidtvClient({ name: "Notifications for Android TV / Fire TV Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = NfandroidtvMapper.toSnapshotFromRaw({ name: "Notifications for Android TV / Fire TV Runtime" }, rawData);
  const devices = NfandroidtvMapper.toDevices(mappedSnapshot);
  const entities = NfandroidtvMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("nfandroidtv");
  expect(devices[0].manufacturer).toEqual("Notifications for Android TV / Fire TV");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "nfandroidtv" && entityArg.platform === "sensor")).toBeTrue();
});

tap.test('checks and sends Notifications for Android TV messages over local HTTP', async () => {
  const requests: string[] = [];
  const postBodies: string[] = [];
  const server = createServer((requestArg, responseArg) => {
    requests.push(`${requestArg.method} ${requestArg.url}`);
    if (requestArg.method === 'GET' && requestArg.url === '/') {
      responseArg.end('ok');
      return;
    }
    if (requestArg.method === 'POST' && requestArg.url === '/') {
      expect(requestArg.headers['content-type']?.startsWith('multipart/form-data; boundary=')).toBeTrue();
      const chunks: Buffer[] = [];
      requestArg.on('data', (chunkArg) => chunks.push(Buffer.isBuffer(chunkArg) ? chunkArg : Buffer.from(chunkArg)));
      requestArg.on('end', () => {
        postBodies.push(Buffer.concat(chunks).toString('utf8'));
        responseArg.end('sent');
      });
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end('not found');
  });

  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 NfandroidtvClient({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();
    const result = await client.execute({ domain: 'nfandroidtv', service: 'send_message', target: {}, data: { message: 'Hello TV', title: 'Title', duration: 3, position: 'center', transparency: '75%', color: 'green', interrupt: true } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(result.success).toBeTrue();
    expect(requests).toEqual(['GET /', 'POST /']);
    expect(postBodies[0]).toContain('name="msg"');
    expect(postBodies[0]).toContain('Hello TV');
    expect(postBodies[0]).toContain('name="position"');
    expect(postBodies[0]).toContain('4');
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Notifications for Android TV / Fire TV runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NfandroidtvIntegration();
  const alias = new HomeAssistantNfandroidtvIntegration();
  expect(alias instanceof NfandroidtvIntegration).toBeTrue();
  expect(alias.domain).toEqual("nfandroidtv");
  expect(integration.status).toEqual("control-runtime");
  expect(nfandroidtvProfile.metadata.configFlow).toEqual(true);
  expect(nfandroidtvProfile.metadata.requirements).toEqual([
    "notifications-android-tv==0.1.5",
  ]);

  const runtime = await integration.setup({ name: "Notifications for Android TV / Fire TV Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "nfandroidtv", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "nfandroidtv", service: 'refresh', target: {} });
  const snapshot = statusResult.data as INfandroidtvSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Notifications for Android TV / Fire TV Device");

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