import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { MfiClient, MfiConfigFlow, MfiIntegration, MfiMapper, createMfiDiscoveryDescriptor, mfiProfile, type IMfiSnapshot, type TMfiRawData } from '../../ts/integrations/mfi/index.js';

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

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

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

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

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

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

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

tap.test('reads and controls Ubiquiti mFi mPort ports over the local HTTP API', async () => {
  const requests: Array<{ url: string; method?: string; body: string; cookie?: string }> = [];
  const commands: Array<Record<string, unknown>> = [];
  const server = createServer((requestArg, responseArg) => {
    const chunks: Buffer[] = [];
    requestArg.on('data', (chunkArg) => chunks.push(Buffer.from(chunkArg)));
    requestArg.on('end', () => {
      const body = Buffer.concat(chunks).toString('utf8');
      requests.push({ url: requestArg.url || '', method: requestArg.method, body, cookie: requestArg.headers.cookie });
      responseArg.setHeader('content-type', 'application/json');

      if (requestArg.url === '/' && requestArg.method === 'GET') {
        responseArg.setHeader('set-cookie', 'preauth=1; Path=/');
        responseArg.end(JSON.stringify({ login: true }));
        return;
      }
      if (requestArg.url === '/login' && requestArg.method === 'POST') {
        const form = new URLSearchParams(body);
        if (form.get('username') === 'admin' && form.get('password') === 'password') {
          responseArg.statusCode = 302;
          responseArg.setHeader('location', '/manage');
          responseArg.setHeader('set-cookie', 'mfi=session; Path=/');
          responseArg.end('');
          return;
        }
        responseArg.statusCode = 403;
        responseArg.end(JSON.stringify({ error: 'bad login' }));
        return;
      }
      if (requestArg.url === '/api/v1.0/stat/device' && requestArg.method === 'GET') {
        responseArg.end(JSON.stringify({ data: [{ _id: 'controller-1', name: 'mPort 3', model: 'M2M', serial: '0418D6FAFC5A', mac: '11:22:33:44:55:66', version: '2.0.25', port_cfg: [{ port: '1', mac: '00:11:22:33:44:55', _id: 'outlet-1', model: 'Outlet', label: 'Heater Control' }, { port: '2', mac: '00:11:22:33:44:66', _id: 'temp-1', model: 'Ubiquiti mFi-THS', label: 'Office Temp' }] }] }));
        return;
      }
      if (requestArg.url === '/api/v1.0/list/sensors' && requestArg.method === 'POST') {
        responseArg.end(JSON.stringify({ data: [{ _id: 'outlet-1', label: 'Heater Control', model: 'Outlet', tag: 'active_pwr', active_pwr: 5.667744, output: 1.0, port: '1', mac: '00:11:22:33:44:55' }, { _id: 'temp-1', label: 'Office Temp', model: 'Ubiquiti mFi-THS', tag: 'temperature', temperature: 21.34, port: '2', mac: '00:11:22:33:44:66' }] }));
        return;
      }
      if (requestArg.url === '/api/v1.0/cmd/devmgr' && requestArg.method === 'POST') {
        const command = JSON.parse(new URLSearchParams(body).get('json') || '{}') as Record<string, unknown>;
        commands.push(command);
        responseArg.end(JSON.stringify({ ok: true }));
        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 MfiClient({ host: '127.0.0.1', port, useTls: false, username: 'admin', password: 'password', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();
    const command = await client.execute({ domain: 'switch', service: 'turn_off', target: { entityId: 'switch.heater_control_switch' } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('mPort 3');
    expect(snapshot.entities.some((entityArg) => entityArg.platform === 'sensor' && entityArg.name === 'Heater Control' && entityArg.state === 6)).toBeTrue();
    expect(snapshot.entities.some((entityArg) => entityArg.platform === 'switch' && entityArg.name === 'Heater Control Switch' && entityArg.state === true)).toBeTrue();
    expect(command.success).toBeTrue();
    expect(commands[0].cmd).toEqual('mfi-output');
    expect(commands[0].sId).toEqual('outlet-1');
    expect(commands[0].val).toEqual(0);
    expect(requests.some((requestArg) => requestArg.url === '/api/v1.0/stat/device' && requestArg.cookie?.includes('mfi=session'))).toBeTrue();
    await client.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Ubiquiti mFi mPort runtime and unsupported control without executor', async () => {
  const integration = new MfiIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(mfiProfile.metadata.configFlow).toEqual(false);
  expect(mfiProfile.metadata.requirements).toEqual([
    "mficlient==0.5.0",
  ]);

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

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

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