/**
 * Payment Method Service - Detects payment method from order data
 * Abstracted logic for determining how an order was paid
 */

import type { SaleorOrder, PaymentMethod } from "../types";
import { paymentMethodConfigs } from "../config";

export class PaymentMethodService {
  /**
   * Detect payment method from order transactions and metadata
   */
  static detectPaymentMethod(order: SaleorOrder): PaymentMethod {
    // Check transactions first
    if (order.transactions && order.transactions.length > 0) {
      const transaction = order.transactions[0];
      const message = transaction.message?.toLowerCase() || "";
      
      // Check transaction events for payment type
      const event = transaction.events?.[0];
      const eventMessage = event?.message?.toLowerCase() || "";
      const eventType = event?.type?.toLowerCase() || "";

      const combinedText = `${message} ${eventMessage} ${eventType}`;

      if (combinedText.includes("cash") || combinedText.includes("cod")) {
        return "cod";
      }
      if (combinedText.includes("card") || combinedText.includes("stripe")) {
        return "card";
      }
      if (combinedText.includes("paypal")) {
        return "paypal";
      }
      if (combinedText.includes("bank") || combinedText.includes("transfer")) {
        return "bank_transfer";
      }
    }

    // Check metadata for payment method
    if (order.metadata) {
      const paymentMeta = order.metadata.find(
        (m) => m.key === "payment_method" || m.key === "paymentMethod"
      );
      if (paymentMeta) {
        const value = paymentMeta.value.toLowerCase();
        if (value.includes("cash") || value.includes("cod")) return "cod";
        if (value.includes("card")) return "card";
        if (value.includes("paypal")) return "paypal";
        if (value.includes("bank")) return "bank_transfer";
      }
    }

    // Default to unknown if no payment method detected
    return "unknown";
  }

  /**
   * Get display label for a payment method
   */
  static getPaymentLabel(method: PaymentMethod): string {
    return paymentMethodConfigs[method]?.label || paymentMethodConfigs.unknown.label;
  }

  /**
   * Get full payment method configuration
   */
  static getPaymentConfig(method: PaymentMethod) {
    return paymentMethodConfigs[method] || paymentMethodConfigs.unknown;
  }
}
