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

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

  async handle(payload: CbeBirrWebhookPayload): Promise<void> {
    const signatureValid = this.provider.verifyWebhookSignature(
      payload as unknown as Record<string, unknown>,
    );
    const mapped = this.provider.mapWebhookStatus(payload.status);
    const providerTxnId = payload.transactionId ?? payload.orderId;

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