import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GoalzeroClient, GoalzeroConfigFlow, GoalzeroIntegration, GoalzeroMapper, HomeAssistantGoalzeroIntegration, createGoalzeroDiscoveryDescriptor, goalzeroProfile, type IGoalzeroSnapshot, type TGoalzeroRawData } from '../../ts/integrations/goalzero/index.js';

const rawData: TGoalzeroRawData = {
  sysdata: {
    macAddress: 'AA:BB:CC:DD:EE:FF',
    model: 'Yeti 1500X',
  },
  data: {
    firmwareVersion: '1.2.3',
    wattsIn: 120,
    wattsOut: 40,
    whStored: 900,
    socPercent: 75,
    timeToEmptyFull: 360,
    temperature: 31,
    wifiStrength: -50,
    ssid: 'camp',
    ipAddr: '192.168.1.42',
    timestamp: 1234,
    app_online: 1,
    backlight: 0,
    isCharging: 1,
    inputDetected: 1,
    v12PortStatus: 1,
    usbPortStatus: 0,
    acPortStatus: 1,
  },
};

tap.test('matches manual Goal Zero candidates and creates config flow output', async () => {
  const descriptor = createGoalzeroDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'goalzero-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'AA:BB:CC:DD:EE:FF', name: 'Yeti', metadata: { rawData } }, {});

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

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

  const done = await (await new GoalzeroConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.name).toEqual('Yeti');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Goal Zero raw snapshots to runtime devices and entities', async () => {
  const client = new GoalzeroClient({ name: 'Goal Zero Yeti', rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = GoalzeroMapper.toSnapshotFromRaw({ name: 'Goal Zero Yeti' }, rawData);
  const devices = GoalzeroMapper.toDevices(mappedSnapshot);
  const entities = GoalzeroMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.device.model).toEqual('Yeti 1500X');
  expect(devices[0].manufacturer).toEqual('Goal Zero');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.goal_zero_yeti_wattsin')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.goal_zero_yeti_ischarging')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.goal_zero_yeti_acportstatus')).toBeTrue();
});

tap.test('exposes Goal Zero read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new GoalzeroIntegration();
  const alias = new HomeAssistantGoalzeroIntegration();
  expect(alias instanceof GoalzeroIntegration).toBeTrue();
  expect(alias.domain).toEqual('goalzero');
  expect(integration.status).toEqual('read-only-runtime');
  expect(goalzeroProfile.metadata.configFlow).toEqual(true);
  expect(goalzeroProfile.metadata.requirements).toEqual(['goalzero==0.2.2']);
  expect(goalzeroProfile.metadata.codeowners).toEqual(['@tkdrob']);

  const runtime = await integration.setup({ name: 'Goal Zero Yeti', rawData }, {});
  const status = await runtime.callService!({ domain: 'goalzero', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'goalzero', service: 'refresh', target: {} });
  const snapshot = status.data as IGoalzeroSnapshot;

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Goal Zero Yeti');

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

export default tap.start();
