import { expect, tap } from '@git.zone/tstest/tapbundle';
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { HomeAssistantOverseerrIntegration, OverseerrClient, OverseerrConfigFlow, OverseerrIntegration, OverseerrMapper, createOverseerrDiscoveryDescriptor, overseerrProfile, type IOverseerrSnapshot, type TOverseerrRawData } from '../../ts/integrations/overseerr/index.js';

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

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

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

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

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

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

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

tap.test('polls Seerr counts and get_requests through the local HTTP API', async () => {
  const requests: Array<{ method?: string; url?: string; apiKey?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    void (async () => {
      requests.push({ method: requestArg.method, url: requestArg.url, apiKey: String(requestArg.headers['x-api-key'] || '') });
      const url = new URL(requestArg.url || '/', 'http://127.0.0.1');
      if (requestArg.headers['x-api-key'] !== 'secret') {
        json(responseArg, { error: 'forbidden' }, 403);
        return;
      }
      if (url.pathname === '/api/v1/request/count') {
        json(responseArg, { total: 7, movie: 3, tv: 4, pending: 1, approved: 2, declined: 1, processing: 1, available: 2 });
        return;
      }
      if (url.pathname === '/api/v1/issue/count') {
        json(responseArg, { total: 5, video: 2, audio: 1, subtitles: 1, others: 1, open: 3, closed: 2 });
        return;
      }
      if (url.pathname === '/api/v1/status') {
        json(responseArg, { version: '1.2.3', updateAvailable: false, commitsBehind: 0, restartRequired: false });
        return;
      }
      if (url.pathname === '/api/v1/request') {
        expect(url.searchParams.get('filter')).toEqual('pending');
        expect(url.searchParams.get('sort')).toEqual('added');
        expect(url.searchParams.get('requestedBy')).toEqual('42');
        json(responseArg, { results: [{ id: 11, status: 1, media: { mediaType: 'movie', tmdbId: 99 }, requestedBy: { id: 42, displayName: 'Ada' }, modifiedBy: null }] });
        return;
      }
      if (url.pathname === '/api/v1/movie/99') {
        json(responseArg, { id: 99, title: 'Example Movie', mediaInfo: { id: 11, mediaType: 'movie', status: 2 } });
        return;
      }
      responseArg.statusCode = 404;
      responseArg.end('{}');
    })().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 OverseerrClient({ url, apiKey: 'secret', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const service = await client.execute({ domain: 'overseerr', service: 'get_requests', target: {}, data: { status: 'pending', sort_order: 'added', requested_by: 42 } });
    const runtime = await new OverseerrIntegration().setup({ url, apiKey: 'secret', timeoutMs: 1000 }, {});
    const status = await runtime.callService!({ domain: 'overseerr', service: 'status', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.model).toEqual('Seerr 1.2.3');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'total_requests')?.state).toEqual(7);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'open_issues')?.state).toEqual(3);
    expect(service.success).toBeTrue();
    expect(((service.data as { requests: Array<{ mediaDetails?: { title?: string } }> }).requests[0].mediaDetails?.title)).toEqual('Example Movie');
    expect((status.data as IOverseerrSnapshot).online).toBeTrue();
    expect(requests.every((requestArg) => requestArg.apiKey === 'secret')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url?.startsWith('/api/v1/request?'))).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Seerr runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OverseerrIntegration();
  const alias = new HomeAssistantOverseerrIntegration();
  expect(alias instanceof OverseerrIntegration).toBeTrue();
  expect(alias.domain).toEqual("overseerr");
  expect(integration.status).toEqual("control-runtime");
  expect(overseerrProfile.metadata.configFlow).toEqual(true);
  expect(overseerrProfile.metadata.requirements).toEqual([
    "python-overseerr==0.9.0",
  ]);

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

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

  const command = await runtime.callService!({ domain: "overseerr", service: 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

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

export default tap.start();
