import { Injectable } from '@angular/core';
import { PosPaymentBridgeAbstract } from './payment-bridge.abstract';

@Injectable({ providedIn: 'root' })
export class PosPaymentBridgeService extends PosPaymentBridgeAbstract {
  registerPaymentResultListener(handler: (payload: unknown) => void): () => void {
    const w = window as unknown as {
      WebV: {
        onPaymentResult?: (payload: unknown) => void;
        AndroidBridge?: {
          onPaymentResult?: (payload: unknown) => void;
        };
      };
    };

    const previousGlobal = w.WebV.onPaymentResult;
    const previousBridge = w.WebV.AndroidBridge?.onPaymentResult;

    w.WebV.onPaymentResult = handler;
    if (w.WebV.AndroidBridge) {
      w.WebV.AndroidBridge.onPaymentResult = handler;
    }

    return () => {
      w.WebV.onPaymentResult = previousGlobal;
      if (w.WebV.AndroidBridge) {
        w.WebV.AndroidBridge.onPaymentResult = previousBridge;
      }
    };
  }

  emitPaymentResultForTest(payload: unknown): void {
    const w = window as unknown as { WebV: { onPaymentResult?: (payload: unknown) => void } };
    w.WebV.onPaymentResult?.(payload);
  }
}
