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

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

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

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