import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPaperlessNgxIntegration, PaperlessNgxClient, PaperlessNgxConfigFlow, PaperlessNgxIntegration, PaperlessNgxMapper, createPaperlessNgxDiscoveryDescriptor, paperlessNgxProfile, type IPaperlessNgxSnapshot, type TPaperlessNgxRawData } from '../../ts/integrations/paperless_ngx/index.js';

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: TPaperlessNgxRawData = {
  device: {
    id: 'paperless_ngx-device-1',
    name: "Paperless-ngx Device",
    manufacturer: "Paperless-ngx",
    model: "Paperless-ngx local integration",
    serialNumber: 'paperless_ngx-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "paperless_ngx" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

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

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

tap.test('reads Paperless-ngx statistics and status over the local HTTP API', async () => {
  const requests: Array<{ method?: string; url?: string; authorization?: string; accept?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
    requests.push({ method: requestArg.method, url: requestArg.url, authorization: requestArg.headers.authorization, accept: requestArg.headers.accept });
    if (requestArg.headers.authorization !== 'Token secret') {
      json(responseArg, { detail: 'invalid token' }, 401);
      return;
    }
    if (url.pathname === '/api/statistics/') {
      json(responseArg, { documents_total: 12, documents_inbox: 3, character_count: 1234, tag_count: 4, correspondent_count: 5, document_type_count: 6 });
      return;
    }
    if (url.pathname === '/api/status/') {
      json(responseArg, { pngx_version: '2.15.0', storage: { total: 10_000_000_000, available: 5_500_000_000 }, database: { status: 'OK' }, tasks: { index_status: 'OK', classifier_status: 'OK', celery_status: 'OK', redis_status: 'OK', sanity_check_status: 'OK' } });
      return;
    }
    if (url.pathname === '/api/remote_version/') {
      json(responseArg, { version: 'v2.16.0' });
      return;
    }
    json(responseArg, { detail: 'not found' }, 404);
  });

  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 PaperlessNgxClient({ url, apiKey: 'secret', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const runtime = await new PaperlessNgxIntegration().setup({ url, apiKey: 'secret', timeoutMs: 1000 }, {});
    const status = await runtime.callService!({ domain: 'paperless_ngx', service: 'status', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.model).toEqual('Paperless-ngx 2.15.0');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'documents_total')?.state).toEqual(12);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'storage_available')?.state).toEqual(5.5);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'database_status')?.state).toEqual('ok');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'paperless_update')?.state).toBeTrue();
    expect(status.success).toBeTrue();
    expect(requests.every((requestArg) => requestArg.authorization === 'Token secret')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.accept === 'application/json; version=7')).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Paperless-ngx runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PaperlessNgxIntegration();
  const alias = new HomeAssistantPaperlessNgxIntegration();
  expect(alias instanceof PaperlessNgxIntegration).toBeTrue();
  expect(alias.domain).toEqual("paperless_ngx");
  expect(integration.status).toEqual("read-only-runtime");
  expect(paperlessNgxProfile.metadata.configFlow).toEqual(true);
  expect(paperlessNgxProfile.metadata.requirements).toEqual([
    "pypaperless==4.1.1",
  ]);

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

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

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