import { ToastService } from '@/core/services/toast.service';
import { inject, Injectable } from '@angular/core';
import { PosPaymentResult } from '../models';
import { PosPaymentBridgeAbstract } from './payment-bridge.abstract';

@Injectable({ providedIn: 'root' })
export class PosPaymentBridgeService extends PosPaymentBridgeAbstract {
  private readonly toastServices = inject(ToastService);
  registerPaymentResultListener(handler: (payload: PosPaymentResult) => void): () => void {
    // @ts-ignore
    window.WebV = {
      onPaymentResult: (payload: PosPaymentResult) => {
        try {
          // const parsedPayload: PosPaymentResult = JSON.parse(payload);
          // this.toastServices.info({ text: payload.data?.customerCardNO || '', life: 10000 });
          // this.toastServices.info({
          //   text: payload.data?.responseCode || 'No response code',
          //   life: 10000,
          // });
          // this.toastServices.info({ text: payload.data?.rrn || 'No response code', life: 10000 });
          // this.toastServices.info({ text: payload.data?.stan || 'No response code', life: 10000 });
          // this.toastServices.info({
          //   text: payload.data?.terminalId || 'No response code',
          //   life: 10000,
          // });
          // this.toastServices.info({
          //   text: payload.data?.transactionDateTime || 'No response code',
          //   life: 10000,
          // });
          handler(payload);
        } catch (e) {
          this.toastServices.error({ text: 'Failed to parse payment result', life: 10000 });
          this.toastServices.error({
            text: e instanceof Error ? e.message : String(e),
            life: 10000,
          });
          this.toastServices.error({ text: typeof payload, life: 10000 });
        }
      },
    };

    return () => {};
  }

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