import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { BaseIntegration } from '../../core/classes.baseintegration.js';
import type { IIntegrationEntity, IIntegrationRuntime, IIntegrationSetupContext, IServiceCallRequest, IServiceCallResult } from '../../core/types.js';
import { WolfSmartsetClient } from './wolf_smartset.classes.client.js';
import { WolfSmartsetConfigFlow } from './wolf_smartset.classes.configflow.js';
import { createWolfSmartsetDiscoveryDescriptor } from './wolf_smartset.discovery.js';
import { WolfSmartsetMapper } from './wolf_smartset.mapper.js';
import type { IWolfSmartsetConfig } from './wolf_smartset.types.js';

export class WolfSmartsetIntegration extends BaseIntegration<IWolfSmartsetConfig> {
  public readonly domain = 'wolf_smartset';
  public readonly displayName = 'Wolf Smartset';
  public readonly status = 'descriptor-only' as const;
  public readonly discoveryDescriptor = createWolfSmartsetDiscoveryDescriptor();
  public readonly configFlow = new WolfSmartsetConfigFlow();

  public async setup(configArg: IWolfSmartsetConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new WolfSmartsetRuntime(new WolfSmartsetClient(configArg));
  }

  public async destroy(): Promise<void> {}
}

class WolfSmartsetRuntime implements IIntegrationRuntime {
  public domain = 'wolf_smartset';

  constructor(private readonly client: WolfSmartsetClient) {}

  public async devices(): Promise<shxInterfaces.data.IDeviceDefinition[]> {
    return WolfSmartsetMapper.toDevices(await this.client.listSystems());
  }

  public async entities(): Promise<IIntegrationEntity[]> {
    return WolfSmartsetMapper.toEntities(await this.client.listSystems());
  }

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.domain !== 'climate' || requestArg.service !== 'set_temperature') {
      return { success: false, error: `Unsupported Wolf Smartset service: ${requestArg.domain}.${requestArg.service}` };
    }
    const deviceId = requestArg.target.deviceId?.replace(/^wolf_smartset\.system\./, '');
    const temperature = requestArg.data?.temperature;
    if (!deviceId || typeof temperature !== 'number') {
      return { success: false, error: 'Wolf Smartset set_temperature requires target.deviceId and data.temperature.' };
    }
    await this.client.setTargetTemperature(deviceId, temperature);
    return { success: true };
  }

  public async destroy(): Promise<void> {
    await this.client.destroy();
  }
}
