import { MikrotikMapper } from './mikrotik.mapper.js';
import type { IMikrotikCommand, IMikrotikCommandResult, IMikrotikConfig, IMikrotikEvent, IMikrotikSnapshot } from './mikrotik.types.js';

type TMikrotikEventHandler = (eventArg: IMikrotikEvent) => void;

export class MikrotikClient {
  private currentSnapshot?: IMikrotikSnapshot;
  private readonly eventHandlers = new Set<TMikrotikEventHandler>();

  constructor(private readonly config: IMikrotikConfig) {}

  public async getSnapshot(): Promise<IMikrotikSnapshot> {
    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);
      }
    }

    const snapshot = this.currentSnapshot ?? MikrotikMapper.toSnapshot(this.config);
    this.currentSnapshot = snapshot;
    return this.cloneSnapshot(snapshot);
  }

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

  public async refresh(): Promise<IMikrotikCommandResult> {
    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 = MikrotikMapper.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: IMikrotikCommand): Promise<IMikrotikCommandResult> {
    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: IMikrotikCommandResult = {
        success: false,
        error: this.unsupportedCommandMessage(commandArg),
        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: IMikrotikCommandResult = { 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: IMikrotikSnapshot, sourceArg: IMikrotikSnapshot['source']): IMikrotikSnapshot {
    const normalized = MikrotikMapper.toSnapshot({ ...this.config, snapshot: this.cloneSnapshot(snapshotArg) }, snapshotArg.connected);
    return { ...normalized, source: snapshotArg.source || sourceArg };
  }

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

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

  private unsupportedCommandMessage(commandArg: IMikrotikCommand): string {
    return `Mikrotik RouterOS/API command ${commandArg.path} is not faked by this native TypeScript port. Provide commandExecutor or nativeClient.executeCommand for live command execution.`;
  }

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

  private cloneSnapshot<T extends IMikrotikSnapshot>(snapshotArg: T): T {
    return JSON.parse(JSON.stringify(snapshotArg)) as T;
  }
}
