import { Injectable } from "@nestjs/common";
import { EBirrProvider, EBirrWebhookPayload } from "@edr/payment-providers";
import { WebhookProcessorService } from "../webhook-processor.service";

@Injectable()
export class EBirrWebhookService {
  constructor(
    private readonly provider: EBirrProvider,
    private readonly processor: WebhookProcessorService,
  ) {}

  async handle(payload: EBirrWebhookPayload): Promise<void> {
    const signatureValid = this.provider.verifyWebhookSignature(
      payload as unknown as Record<string, unknown>,
    );
    const mapped = this.provider.mapWebhookStatus(payload.tradeStatus);

    await this.processor.process({
      provider: this.provider.method,
      externalEventId: `${payload.orderNo}_${payload.tradeStatus}_${payload.timestamp}`,
      merchantOrderId: payload.orderNo,
      providerTxnId: payload.tradeNo,
      signatureValid,
      rawStatus: payload.tradeStatus,
      payload: payload as unknown as Record<string, unknown>,
      result: {
        status: mapped,
        providerTxnId: payload.tradeNo,
        failureCode: payload.tradeStatus,
      },
    });
  }
}
