import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FritzboxCallmonitorMapper, type IFritzboxCallmonitorConfig } from '../../ts/integrations/fritzbox_callmonitor/index.js';

const config: IFritzboxCallmonitorConfig = {
  host: '192.168.178.1',
  port: 1012,
  phonebookName: 'Phone',
  serialNumber: 'AABBCCDDEEFF',
  prefixes: ['+49'],
  contacts: [{ name: 'Alice', numbers: ['+4930123456'], vip: true }],
};

tap.test('parses FRITZ!Box call monitor RING CALL CONNECT and DISCONNECT lines', async () => {
  const contacts = FritzboxCallmonitorMapper.normalizeContacts(config.contacts || []);
  const ring = FritzboxCallmonitorMapper.parseEvent('01.01.26 12:00:00;RING;0;030123456;+4930999;SIP0;', contacts, config.prefixes);
  const call = FritzboxCallmonitorMapper.parseEvent('01.01.26 12:01:00;CALL;1;SIP1;+4930999;030123456;SIP1;', contacts, config.prefixes);
  const connect = FritzboxCallmonitorMapper.parseEvent('01.01.26 12:02:00;CONNECT;1;SIP1;030123456;', contacts, config.prefixes);
  const disconnect = FritzboxCallmonitorMapper.parseEvent('01.01.26 12:03:00;DISCONNECT;1;60;', contacts, config.prefixes);

  expect(ring.callState).toEqual('ringing');
  expect(ring.attributes.from_name).toEqual('Alice');
  expect(ring.attributes.vip).toBeTrue();
  expect(call.callState).toEqual('dialing');
  expect(call.attributes.to_name).toEqual('Alice');
  expect(connect.callState).toEqual('talking');
  expect(connect.attributes.with_name).toEqual('Alice');
  expect(disconnect.callState).toEqual('idle');
  expect(disconnect.attributes.duration).toEqual('60');
  expect(disconnect.attributes.closed).toEqual('2026-01-01T12:03:00');
});

tap.test('maps snapshots to one device and Home Assistant style sensor entities', async () => {
  const snapshot = FritzboxCallmonitorMapper.toSnapshot({
    ...config,
    eventLines: [
      '01.01.26 12:00:00;RING;0;030123456;+4930999;SIP0;',
      '01.01.26 12:03:00;DISCONNECT;0;180;',
    ],
  });
  const devices = FritzboxCallmonitorMapper.toDevices(snapshot);
  const entities = FritzboxCallmonitorMapper.toEntities(snapshot);
  const sensor = entities.find((entityArg) => entityArg.id === 'sensor.phone_call_monitor');

  expect(devices[0].id).toEqual('fritzbox_callmonitor.monitor.aabbccddeeff');
  expect(snapshot.call.state).toEqual('idle');
  expect(sensor?.state).toEqual('idle');
  expect(sensor?.attributes?.duration).toEqual('180');
  expect(sensor?.attributes?.prefixes).toEqual(['+49']);
  expect(entities.find((entityArg) => entityArg.id === 'binary_sensor.phone_call_monitor_connection')?.state).toEqual('on');
});

export default tap.start();
