import { SimpleLocalClient } from '../../core/index.js';
import { EnphaseEnvoyMapper } from './enphase_envoy.mapper.js';
import type { IEnphaseEnvoyConfig, IEnphaseEnvoySnapshot } from './enphase_envoy.types.js';
import { enphaseEnvoyProfile } from './enphase_envoy.types.js';

export class EnphaseEnvoyClient extends SimpleLocalClient<IEnphaseEnvoyConfig> {
  private readonly configArg: IEnphaseEnvoyConfig;

  constructor(configArg: IEnphaseEnvoyConfig) {
    const runtimeConfig = configArg.rawData !== undefined || configArg.entities?.length || configArg.snapshot ? { ...configArg, host: undefined, path: undefined, transport: 'snapshot' as const } : configArg;
    super(enphaseEnvoyProfile, runtimeConfig);
    this.configArg = configArg;
  }

  public async getSnapshot(forceRefreshArg = false): Promise<IEnphaseEnvoySnapshot> {
    const snapshot = await super.getSnapshot(forceRefreshArg);
    if (snapshot.rawData === undefined && snapshot.entities.length) {
      return EnphaseEnvoyMapper.toSnapshot({ config: { ...this.configArg, snapshot }, online: snapshot.online, source: snapshot.source, error: snapshot.error });
    }

    return EnphaseEnvoyMapper.toSnapshot({ config: this.configArg, rawData: snapshot.rawData, online: snapshot.online, source: snapshot.source, error: snapshot.error });
  }
}
