import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EcoalBoilerClient, EcoalBoilerConfigFlow, EcoalBoilerIntegration, EcoalBoilerMapper, HomeAssistantEcoalBoilerIntegration, ecoalBoilerProfile, createEcoalBoilerDiscoveryDescriptor, type IEcoalBoilerSnapshot } from '../../ts/integrations/ecoal_boiler/index.js';

const rawData = {
  device: {
    id: 'ecoal-1234',
    name: 'Boiler room eCoal',
    serialNumber: 'ecoal-1234',
  },
  entities: [
    {
      id: 'outdoor_temp',
      name: 'Outdoor temperature',
      platform: 'sensor',
      state: 8.5,
      unit: 'C',
      deviceClass: 'temperature',
    },
    {
      id: 'domestic_hot_water_temp',
      name: 'Domestic hot water temperature',
      platform: 'sensor',
      state: 47,
      unit: 'C',
      deviceClass: 'temperature',
    },
    {
      id: 'central_heating_pump',
      name: 'Central heating pump',
      platform: 'switch',
      state: true,
      writable: true,
    },
  ],
};

tap.test('defines the eCoal Boiler simple-local profile and HA alias', async () => {
  const integration = new HomeAssistantEcoalBoilerIntegration();

  expect(integration).toBeInstanceOf(EcoalBoilerIntegration);
  expect(integration.domain).toEqual('ecoal_boiler');
  expect(integration.status).toEqual('control-runtime');
  expect(ecoalBoilerProfile.metadata.upstreamPath).toEqual('homeassistant/components/ecoal_boiler');
  expect(ecoalBoilerProfile.metadata.qualityScale).toEqual('legacy');
  expect(ecoalBoilerProfile.metadata.requirements).toEqual(['ecoaliface==0.4.0']);
  expect(ecoalBoilerProfile.metadata.configFlow).toBeFalse();
});

tap.test('matches manual eCoal Boiler candidates and creates config flow output', async () => {
  const descriptor = createEcoalBoilerDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'ecoal_boiler-manual-match');
  const result = await matcher!.matches({ host: 'ecoal.local', name: 'eSterownik eCoal.pl Boiler', metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('ecoal_boiler');

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

  const done = await (await new EcoalBoilerConfigFlow().start(result.candidate!, {})).submit!({ username: 'admin' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('ecoal.local');
  expect(done.config?.username).toEqual('admin');
});

tap.test('maps eCoal Boiler raw snapshots to runtime devices and entities', async () => {
  const client = new EcoalBoilerClient({ name: 'eCoal Boiler Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = EcoalBoilerMapper.toDevices(snapshot);
  const entities = EcoalBoilerMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('ecoal_boiler');
  expect(devices[0].manufacturer).toEqual('eSterownik');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.boiler_room_ecoal_outdoor_temp')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.boiler_room_ecoal_central_heating_pump')).toBeTrue();
});

tap.test('exposes eCoal Boiler runtime services without fake live control', async () => {
  const runtime = await new EcoalBoilerIntegration().setup({ name: 'eCoal Boiler Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'ecoal_boiler', service: 'status', target: {} });
  const snapshot = status.data as IEcoalBoilerSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Boiler room eCoal');

  const liveCommand = await runtime.callService!({ domain: 'switch', service: 'turn_on', target: {} });
  expect(liveCommand.success).toBeFalse();
  expect(liveCommand.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();

  const executorRuntime = await new EcoalBoilerIntegration().setup({
    name: 'eCoal Boiler Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'switch', service: 'turn_off', target: {} });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('turn_off');
  await executorRuntime.destroy();
});

export default tap.start();
