import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMutesyncIntegration, MutesyncClient, MutesyncConfigFlow, MutesyncIntegration, MutesyncMapper, createMutesyncDiscoveryDescriptor, mutesyncProfile, type IMutesyncSnapshot, type TMutesyncRawData } from '../../ts/integrations/mutesync/index.js';

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

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

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

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

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

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

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

tap.test('authenticates and reads mutesync state over the local HTTP API', async () => {
  const requests: Array<{ url: string; authorization?: string; apiVersion?: string }> = [];
  const server = createServer((requestArg, responseArg) => {
    requests.push({
      url: requestArg.url || '',
      authorization: requestArg.headers.authorization,
      apiVersion: requestArg.headers['x-mutesync-api-version'] as string | undefined,
    });
    responseArg.setHeader('content-type', 'application/json');
    if (requestArg.url === '/authenticate') {
      responseArg.end(JSON.stringify({ token: 'local-token' }));
      return;
    }
    if (requestArg.url === '/state') {
      responseArg.end(JSON.stringify({ data: { muted: true, in_meeting: false, 'user-id': 'user-1' } }));
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end(JSON.stringify({ error: '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 MutesyncClient({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const runtime = await new MutesyncIntegration().setup({ host: '127.0.0.1', port, timeoutMs: 1000 }, {});
    const entities = await runtime.entities();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.id).toEqual('user-1');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'muted')?.state).toBeTrue();
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'in_meeting')?.state).toBeFalse();
    expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.mutesync_muted' && entityArg.state === true)).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/authenticate')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/state' && requestArg.authorization === 'Token local-token' && requestArg.apiVersion === '1')).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes mutesync runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MutesyncIntegration();
  const alias = new HomeAssistantMutesyncIntegration();
  expect(alias instanceof MutesyncIntegration).toBeTrue();
  expect(alias.domain).toEqual("mutesync");
  expect(integration.status).toEqual("read-only-runtime");
  expect(mutesyncProfile.metadata.configFlow).toEqual(true);
  expect(mutesyncProfile.metadata.requirements).toEqual([
    "mutesync==0.0.1",
  ]);
  expect(String((mutesyncProfile.metadata.localApi as Record<string, unknown>).status)).toContain('port 8249');

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

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

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