import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPeblarIntegration, PeblarClient, PeblarConfigFlow, PeblarIntegration, PeblarMapper, createPeblarDiscoveryDescriptor, peblarProfile, type IPeblarSnapshot, type TPeblarRawData } from '../../ts/integrations/peblar/index.js';

const readBody = async (requestArg: IncomingMessage): Promise<string> => {
  const chunks: Buffer[] = [];
  for await (const chunk of requestArg) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  return Buffer.concat(chunks).toString('utf8');
};

const json = (responseArg: ServerResponse, valueArg: unknown, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'application/json');
  responseArg.end(JSON.stringify(valueArg));
};

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

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

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

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

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

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

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

tap.test('logs in and reads Peblar local REST data over HTTP', async () => {
  const requests: Array<{ method?: string; url?: string; body?: string; authorization?: string; cookie?: string }> = [];
  let chargeCurrentLimit = 16000;
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    void (async () => {
      const body = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(requestArg.method || '') ? await readBody(requestArg) : undefined;
      const authorization = typeof requestArg.headers.authorization === 'string' ? requestArg.headers.authorization : undefined;
      const cookie = typeof requestArg.headers.cookie === 'string' ? requestArg.headers.cookie : undefined;
      requests.push({ method: requestArg.method, url: requestArg.url, body, authorization, cookie });
      const url = new URL(requestArg.url || '/', 'http://127.0.0.1');

      if (url.pathname === '/api/v1/auth/login' && requestArg.method === 'POST') {
        expect(body!).toContain('Password');
        responseArg.setHeader('set-cookie', 'session=abc; Path=/');
        json(responseArg, {});
        return;
      }
      if (url.pathname.startsWith('/api/v1/') && cookie !== 'session=abc') {
        json(responseArg, { error: 'missing cookie' }, 401);
        return;
      }
      if (url.pathname === '/api/v1/system/info') {
        json(responseArg, { ProductSn: 'PEB123', ProductModelName: 'Peblar Home', ProductVendorName: 'Peblar', Hostname: 'peblar-test', FwIdent: '1.2.3', EthMacAddr: 'AA:BB:CC:DD:EE:FF', WlanStaMacAddr: '11:22:33:44:55:66' });
        return;
      }
      if (url.pathname === '/api/v1/config/user' && requestArg.method === 'GET') {
        json(responseArg, { LocalRestApiAllowed: true, LocalRestApiEnable: false, LocalRestApiAccessMode: 'ReadOnly', ConnectedPhases: 3, ScheduledChargingEnable: false, SolarChargingEnable: false, UserDefinedChargeLimitCurrent: 32 });
        return;
      }
      if (url.pathname === '/api/v1/config/user' && requestArg.method === 'PATCH') {
        json(responseArg, {});
        return;
      }
      if (url.pathname === '/api/v1/config/api-token') {
        json(responseArg, { ApiToken: 'rest-token' });
        return;
      }
      if (url.pathname === '/api/v1/system/software/automatic-update/current-versions') {
        json(responseArg, { Firmware: '1.2.3', Customization: 'Peblar-1.0' });
        return;
      }
      if (url.pathname === '/api/v1/system/software/automatic-update/available-versions') {
        json(responseArg, { Firmware: '1.2.4', Customization: 'Peblar-1.0' });
        return;
      }
      if (url.pathname === '/api/v1/system/identify' && requestArg.method === 'PUT') {
        json(responseArg, {});
        return;
      }
      if (url.pathname.startsWith('/api/wlac/v1/') && authorization !== 'rest-token') {
        json(responseArg, { error: 'missing token' }, 401);
        return;
      }
      if (url.pathname === '/api/wlac/v1/evinterface' && requestArg.method === 'GET') {
        json(responseArg, { ChargeCurrentLimit: chargeCurrentLimit, ChargeCurrentLimitActual: chargeCurrentLimit, ChargeCurrentLimitSource: 'Local REST API', CpState: 'State C', Force1Phase: false, LockState: true });
        return;
      }
      if (url.pathname === '/api/wlac/v1/evinterface' && requestArg.method === 'PATCH') {
        const parsed = JSON.parse(body || '{}') as { ChargeCurrentLimit?: number };
        if (typeof parsed.ChargeCurrentLimit === 'number') {
          chargeCurrentLimit = parsed.ChargeCurrentLimit;
        }
        json(responseArg, { ChargeCurrentLimit: chargeCurrentLimit, ChargeCurrentLimitActual: chargeCurrentLimit, ChargeCurrentLimitSource: 'Local REST API', CpState: 'State C', Force1Phase: false, LockState: true });
        return;
      }
      if (url.pathname === '/api/wlac/v1/meter') {
        json(responseArg, { CurrentPhase1: 1000, CurrentPhase2: 2000, CurrentPhase3: 3000, EnergySession: 1200, EnergyTotal: 345600, PowerPhase1: 100, PowerPhase2: 200, PowerPhase3: 300, PowerTotal: 600, VoltagePhase1: 230, VoltagePhase2: 231, VoltagePhase3: 232 });
        return;
      }
      if (url.pathname === '/api/wlac/v1/system') {
        json(responseArg, { ActiveErrorCodes: [], ActiveWarningCodes: ['W1'], FirmwareVersion: '1.2.3', Force1PhaseAllowed: true, PhaseCount: 3, ProductPn: 'PBL-HOME', ProductSn: 'PEB123', Uptime: 3600, WlanSignalStrength: -45 });
        return;
      }
      json(responseArg, { error: 'not found' }, 404);
    })().catch((errorArg) => {
      responseArg.statusCode = 500;
      responseArg.end(String(errorArg));
    });
  });

  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 url = `http://127.0.0.1:${port}`;
    const client = new PeblarClient({ url, password: 'secret', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const setValue = await client.execute({ domain: 'peblar', service: 'set_value', target: {}, data: { value: 10 } });
    const identify = await client.execute({ domain: 'peblar', service: 'press', target: {}, data: { button: 'identify' } });
    const runtime = await new PeblarIntegration().setup({ url, password: 'secret', timeoutMs: 1000 }, {});
    const status = await runtime.callService!({ domain: 'peblar', service: 'status', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('PEB123');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'cp_state')?.state).toEqual('charging');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'current_total')?.state).toEqual(6000);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'charge_current_limit')?.state).toEqual(16);
    expect(setValue.success).toBeTrue();
    expect(identify.success).toBeTrue();
    expect(status.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/api/v1/config/user' && requestArg.method === 'PATCH' && requestArg.body?.includes('LocalRestApiEnable'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/api/wlac/v1/evinterface' && requestArg.method === 'PATCH' && requestArg.body?.includes('10000'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.authorization === 'rest-token')).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Peblar runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PeblarIntegration();
  const alias = new HomeAssistantPeblarIntegration();
  expect(alias instanceof PeblarIntegration).toBeTrue();
  expect(alias.domain).toEqual("peblar");
  expect(integration.status).toEqual("control-runtime");
  expect(peblarProfile.metadata.configFlow).toEqual(true);
  expect(peblarProfile.metadata.requirements).toEqual([
    "peblar==0.5.1",
  ]);

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

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

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