import type { IOpnsenseCommand, IOpnsenseCommandResult, IOpnsenseConfig, IOpnsenseEvent, IOpnsenseSnapshot } from './opnsense.types.js';
import { OpnsenseMapper } from './opnsense.mapper.js';

type TOpnsenseEventHandler = (eventArg: IOpnsenseEvent) => void;

export class OpnsenseClient {
  private currentSnapshot?: IOpnsenseSnapshot;
  private readonly eventHandlers = new Set<TOpnsenseEventHandler>();

  constructor(private readonly config: IOpnsenseConfig) {}

  public async getSnapshot(): Promise<IOpnsenseSnapshot> {
    if (this.config.nativeClient) {
      this.currentSnapshot = this.normalizeSnapshot(await this.config.nativeClient.getSnapshot(), 'provider');
      return this.cloneSnapshot(this.currentSnapshot);
    }

    if (this.config.snapshotProvider) {
      const provided = await this.config.snapshotProvider();
      if (provided) {
        this.currentSnapshot = this.normalizeSnapshot(provided, 'provider');
        return this.cloneSnapshot(this.currentSnapshot);
      }
    }

    if (!this.currentSnapshot) {
      this.currentSnapshot = OpnsenseMapper.toSnapshot(this.config);
    }
    return this.cloneSnapshot(this.currentSnapshot);
  }

  public onEvent(handlerArg: TOpnsenseEventHandler): () => void {
    this.eventHandlers.add(handlerArg);
    return () => this.eventHandlers.delete(handlerArg);
  }

  public async refresh(): Promise<IOpnsenseCommandResult> {
    try {
      this.currentSnapshot = undefined;
      const snapshot = await this.getSnapshot();
      this.emit({ type: 'snapshot_refreshed', snapshot, timestamp: Date.now() });
      return { success: true, data: snapshot };
    } catch (errorArg) {
      const error = errorArg instanceof Error ? errorArg.message : String(errorArg);
      const snapshot = OpnsenseMapper.toSnapshot({ ...this.config, connected: false, snapshot: this.currentSnapshot }, false);
      this.currentSnapshot = snapshot;
      this.emit({ type: 'refresh_failed', snapshot, error, timestamp: Date.now() });
      return { success: false, error, data: snapshot };
    }
  }

  public async sendCommand(commandArg: IOpnsenseCommand): Promise<IOpnsenseCommandResult> {
    this.emit({ type: 'command_mapped', command: commandArg, deviceId: commandArg.deviceId, entityId: commandArg.entityId, timestamp: Date.now() });

    const executor = this.config.commandExecutor || this.config.nativeClient?.executeCommand?.bind(this.config.nativeClient);
    if (!executor) {
      const result: IOpnsenseCommandResult = {
        success: false,
        error: 'OPNsense live API commands are not faked by this native TypeScript port. Provide commandExecutor or nativeClient.executeCommand for reboot, service, firewall, VPN, interface, firmware, or switch actions.',
        data: { command: commandArg },
      };
      this.emit({ type: 'command_failed', command: commandArg, data: result, deviceId: commandArg.deviceId, entityId: commandArg.entityId, timestamp: Date.now() });
      return result;
    }

    try {
      const result = this.commandResult(await executor(commandArg), commandArg);
      this.emit({ type: result.success ? 'command_executed' : 'command_failed', command: commandArg, data: result, deviceId: commandArg.deviceId, entityId: commandArg.entityId, timestamp: Date.now() });
      return result;
    } catch (errorArg) {
      const result: IOpnsenseCommandResult = { success: false, error: errorArg instanceof Error ? errorArg.message : String(errorArg), data: { command: commandArg } };
      this.emit({ type: 'command_failed', command: commandArg, data: result, deviceId: commandArg.deviceId, entityId: commandArg.entityId, timestamp: Date.now() });
      return result;
    }
  }

  public async destroy(): Promise<void> {
    await this.config.nativeClient?.destroy?.();
    this.eventHandlers.clear();
  }

  private normalizeSnapshot(snapshotArg: IOpnsenseSnapshot, sourceArg: IOpnsenseSnapshot['source']): IOpnsenseSnapshot {
    const normalized = OpnsenseMapper.toSnapshot({ ...this.config, snapshot: this.cloneSnapshot(snapshotArg) }, snapshotArg.connected);
    return { ...normalized, source: snapshotArg.source || sourceArg };
  }

  private commandResult(resultArg: unknown, commandArg: IOpnsenseCommand): IOpnsenseCommandResult {
    if (this.isCommandResult(resultArg)) {
      return resultArg;
    }
    return { success: true, data: resultArg ?? { command: commandArg } };
  }

  private isCommandResult(valueArg: unknown): valueArg is IOpnsenseCommandResult {
    return Boolean(valueArg && typeof valueArg === 'object' && 'success' in valueArg);
  }

  private emit(eventArg: IOpnsenseEvent): void {
    for (const handler of this.eventHandlers) {
      handler(eventArg);
    }
  }

  private cloneSnapshot<T extends IOpnsenseSnapshot | undefined>(snapshotArg: T): T {
    return snapshotArg ? JSON.parse(JSON.stringify(snapshotArg)) as T : snapshotArg;
  }
}
