import { expect, tap } from '@git.zone/tstest/tapbundle';
import { BrotherClient, BrotherIntegration, BrotherMapper, brotherOids, type IBrotherRawData } from '../../ts/integrations/brother/index.js';

const rawData: IBrotherRawData = {
  [brotherOids.model]: 'MFG:Brother;MDL:MFC-L3770CDW;CMD:PCL;',
  [brotherOids.serial]: 'COLOR123',
  [brotherOids.status]: 'Printing',
  [brotherOids.counters]: ['000104000001f4', '01010400000190', '02010400000064'],
  [brotherOids.maintenance]: ['6f010400002328', '70010400001f40', '71010400001b58', '72010400001770'],
};

tap.test('reads Brother snapshots from an injected SNMP-style client', async () => {
  const client = new BrotherClient({
    host: 'printer.local',
    client: {
      getRawData: async () => rawData,
    },
  });
  const snapshot = await client.getSnapshot();

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('client');
  expect(snapshot.printer.model).toEqual('MFC-L3770CDW');
  expect(snapshot.sensors.status).toEqual('printing');
  expect(snapshot.sensors.page_counter).toEqual(500);
  expect(snapshot.sensors.black_toner_remaining).toEqual(90);
  expect(await client.ping()).toBeTrue();
});

tap.test('read-only Brother runtime exposes snapshots and refuses unsupported writes', async () => {
  const snapshot = BrotherMapper.toSnapshot({
    config: { name: 'Runtime Brother', model: 'HL-L2350DW', serial: 'RUN123' },
    sensors: { status: 'ready', page_counter: 42, black_toner_remaining: 77 },
    online: true,
    source: 'manual',
  });
  const runtime = await new BrotherIntegration().setup({ snapshot }, {});

  const snapshotResult = await runtime.callService?.({ domain: 'brother', service: 'snapshot', target: {} });
  expect(snapshotResult?.success).toBeTrue();
  const unsupported = await runtime.callService?.({ domain: 'brother', service: 'set_datetime', target: {} });
  expect(unsupported?.success).toBeFalse();
  expect(unsupported?.error).toContain('read-only');
  expect((await runtime.entities()).find((entityArg) => entityArg.attributes?.key === 'page_counter')?.state).toEqual(42);
  await runtime.destroy();
});

tap.test('refresh reports failure when only a host is configured', async () => {
  const runtime = await new BrotherIntegration().setup({ host: 'printer.local' }, {});
  const result = await runtime.callService?.({ domain: 'brother', service: 'refresh', target: {} });

  expect(result?.success).toBeFalse();
  expect(result?.error).toContain('Native Brother SNMP transport is not implemented');
  await runtime.destroy();
});

export default tap.start();
