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

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

  async handle(payload: TelebirrWebhookPayload): Promise<void> {
    // TODO: re-enable Telebirr public-key signature verification — skipped for now
    // (carried over from the passenger handler; see telebirr.provider verifyWebhookSignature).
    const signatureValid = true;

    const mapped = this.provider.mapWebhookTradeStatus(payload.trade_status);
    const providerTxnId = payload.trans_id ?? payload.payment_order_id;

    await this.processor.process({
      provider: this.provider.method,
      externalEventId: `${payload.payment_order_id}_${payload.trade_status}`,
      merchantOrderId: payload.merch_order_id,
      providerTxnId,
      signatureValid,
      rawStatus: payload.trade_status,
      payload: payload as unknown as Record<string, unknown>,
      result: {
        status: mapped,
        providerTxnId,
        paidAt: this.parseEpoch(payload.trans_end_time),
        failureCode: payload.trade_status,
      },
    });
  }
  private parseEpoch(raw: string | undefined): Date | undefined {
    if (!raw) return undefined;
    const n = parseInt(raw, 10);
    if (Number.isNaN(n)) return undefined;
    return new Date(n < 1e12 ? n * 1000 : n);
  }
}
