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

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

  async handle(payload: CardWebhookPayload, signature: string): Promise<void> {
    const signatureValid = this.provider.verifyWebhookSignature(
      payload as unknown as Record<string, unknown>,
      signature,
    );
    const object = payload.data.object;
    const mapped = this.provider.mapWebhookStatus(object.status);

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