import { SimpleLocalClient } from '../../core/index.js';
import { OwntracksMapper } from './owntracks.mapper.js';
import type { IOwntracksConfig, IOwntracksSnapshot } from './owntracks.types.js';
import { owntracksDefaultName, owntracksProfile } from './owntracks.types.js';

export class OwntracksClient extends SimpleLocalClient<IOwntracksConfig> {
  constructor(private readonly configArg: IOwntracksConfig) {
    super(owntracksProfile, configArg);
  }

  public async getSnapshot(forceRefreshArg = false): Promise<IOwntracksSnapshot> {
    if (this.hasUnsafeLiveEndpoint() && !this.hasSafeOfflineSource()) {
      return this.offlineOwntracksSnapshot('OwnTracks is push-only: live updates require an inbound webhook or MQTT broker subscription, not a client-side HTTP polling endpoint.');
    }

    return await super.getSnapshot(forceRefreshArg) as IOwntracksSnapshot;
  }

  private hasUnsafeLiveEndpoint(): boolean {
    return Boolean(this.configArg.host || this.configArg.url || this.configArg.path || this.configArg.transport === 'http' || String(this.configArg.transport) === 'mqtt');
  }

  private hasSafeOfflineSource(): boolean {
    return Boolean(this.configArg.client || this.configArg.snapshotProvider || this.configArg.snapshot || this.configArg.rawData !== undefined || this.configArg.rawText !== undefined || this.configArg.entities?.length);
  }

  private offlineOwntracksSnapshot(errorArg: string): IOwntracksSnapshot {
    return OwntracksMapper.toSnapshot({
      config: this.configArg,
      rawData: {
        device: {
          id: this.configArg.uniqueId || this.configArg.deviceId || owntracksProfile.domain,
          name: this.configArg.name || owntracksDefaultName,
          manufacturer: 'OwnTracks',
          model: 'OwnTracks push ingestion',
        },
        entities: [{ id: 'online', name: 'Online', platform: 'binary_sensor', state: false, available: true, attributes: { error: errorArg } }],
        online: false,
        updatedAt: new Date().toISOString(),
        source: 'runtime',
        error: errorArg,
      },
      online: false,
      source: 'runtime',
      error: errorArg,
    }) as IOwntracksSnapshot;
  }
}
