import { SimpleLocalClient } from '../../core/index.js';
import { HegelMapper } from './hegel.mapper.js';
import type { IHegelConfig, IHegelSnapshot } from './hegel.types.js';
import { hegelProfile } from './hegel.types.js';

export class HegelClient extends SimpleLocalClient<IHegelConfig> {
  constructor(private readonly configArg: IHegelConfig) {
    super(hegelProfile, configArg);
  }

  public async getSnapshot(forceRefreshArg = false): Promise<IHegelSnapshot> {
    if (!this.configArg.client && !this.configArg.snapshotProvider && (this.configArg.snapshot || this.configArg.rawData !== undefined || this.configArg.rawText !== undefined || this.configArg.entities?.length)) {
      return HegelMapper.toSnapshot({
        config: this.configArg,
        rawData: this.configArg.snapshot ?? this.configArg.rawData ?? this.configArg.rawText,
        online: this.configArg.online ?? true,
        source: this.configArg.snapshot ? 'snapshot' : 'manual',
      });
    }

    const snapshot = await super.getSnapshot(forceRefreshArg);
    if (snapshot.rawData === undefined && snapshot.entities.length) {
      return HegelMapper.toSnapshot({ config: { ...this.configArg, snapshot }, online: snapshot.online, source: snapshot.source, error: snapshot.error });
    }

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