import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { MillClient, MillConfigFlow, MillIntegration, MillMapper, createMillDiscoveryDescriptor, millProfile, type IMillSnapshot, type TMillRawData } from '../../ts/integrations/mill/index.js';

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

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

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

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

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

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

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

tap.test('reads and controls Mill Gen 3 heaters over the local HTTP API', async () => {
  const requests: Array<{ url: string; method?: string; body: string }> = [];
  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 });
      responseArg.setHeader('content-type', 'application/json');

      if (requestArg.url === '/status' && requestArg.method === 'GET') {
        responseArg.end(JSON.stringify({ name: 'Office Mill', version: '3.4.5', mac_address: 'aa:bb:cc:dd:ee:ff' }));
        return;
      }
      if (requestArg.url === '/control-status' && requestArg.method === 'GET') {
        responseArg.end(JSON.stringify({ set_temperature: 22, ambient_temperature: 20.5, operation_mode: 'Control individually', current_power: 450, control_signal: 35, raw_ambient_temperature: 20.1 }));
        return;
      }
      if (requestArg.url === '/set-temperature' && requestArg.method === 'POST') {
        responseArg.end(JSON.stringify({ status: 'ok' }));
        return;
      }
      if (requestArg.url === '/operation-mode' && requestArg.method === 'POST') {
        responseArg.end(JSON.stringify({ status: 'ok' }));
        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 MillClient({ host: '127.0.0.1', port, timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('Office Mill');
    expect(snapshot.entities.some((entityArg) => entityArg.platform === 'climate' && entityArg.state === 'heat' && entityArg.attributes?.targetTemperature === 22)).toBeTrue();
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'current_power' && entityArg.state === 450)).toBeTrue();

    const runtime = await new MillIntegration().setup({ host: '127.0.0.1', port, timeoutMs: 1000 }, {});
    const temperature = await runtime.callService!({ domain: 'climate', service: 'set_temperature', target: { entityId: 'climate.office_mill' }, data: { temperature: 18.5 } });
    const mode = await runtime.callService!({ domain: 'climate', service: 'set_hvac_mode', target: { entityId: 'climate.office_mill' }, data: { hvac_mode: 'auto' } });

    expect(temperature.success).toBeTrue();
    expect(mode.success).toBeTrue();
    const temperatureBody = JSON.parse(requests.find((requestArg) => requestArg.url === '/set-temperature')!.body) as Record<string, unknown>;
    const modeBody = JSON.parse(requests.find((requestArg) => requestArg.url === '/operation-mode')!.body) as Record<string, unknown>;
    expect(temperatureBody.type).toEqual('Normal');
    expect(temperatureBody.value).toEqual(18.5);
    expect(modeBody.mode).toEqual('Weekly program');
    await runtime.destroy();
    await client.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Mill runtime and unsupported control without executor', async () => {
  const integration = new MillIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(millProfile.metadata.configFlow).toEqual(true);
  expect(millProfile.metadata.requirements).toEqual([
    "millheater==0.14.1",
    "mill-local==0.5.0",
  ]);

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

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

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