/**
 * Order Transformer Service - Transforms Saleor order data into normalized email data
 * All transformation logic abstracted here instead of inline in templates
 */

import type { 
  SaleorOrder, 
  EmailData, 
  AdminEmailData, 
  LanguageCode,
  OrderLine 
} from "../types";
import { 
  localeConfigs, 
  DEFAULT_LANGUAGE, 
  DEFAULT_CURRENCY 
} from "../config";
import { PaymentMethodService } from "./paymentMethodService";

export class OrderTransformerService {
  /**
   * Extract and format customer name from order
   */
  static extractCustomerName(order: SaleorOrder): string {
    if (order.shippingAddress?.firstName) {
      return `${order.shippingAddress.firstName} ${order.shippingAddress.lastName || ""}`.trim();
    }
    if (order.billingAddress?.firstName) {
      return `${order.billingAddress.firstName} ${order.billingAddress.lastName || ""}`.trim();
    }
    if (order.userEmail) {
      return order.userEmail.split("@")[0];
    }
    return "Customer";
  }

  /**
   * Format shipping address for display
   */
  static formatShippingAddress(order: SaleorOrder): string {
    const address = order.shippingAddress;
    if (!address) return "";

    const parts = [
      `${address.firstName || ""} ${address.lastName || ""}`.trim(),
      address.streetAddress1,
      address.streetAddress2,
      `${address.city || ""}${address.postalCode ? `, ${address.postalCode}` : ""}`,
      address.country?.country || address.country?.code,
    ].filter(Boolean);

    return parts.join("\n");
  }

  /**
   * Extract phone number with fallback
   */
  static extractPhone(order: SaleorOrder): string {
    return (
      order.shippingAddress?.phone ||
      order.billingAddress?.phone ||
      ""
    );
  }

  /**
   * Format order items for email
   */
  static formatItems(order: SaleorOrder): Array<{
    name: string;
    quantity: number;
    price: string;
  }> {
    const currency = order.total?.gross?.currency || DEFAULT_CURRENCY;

    return (order.lines || []).map((line: OrderLine) => {
      const productName = line.variant?.product?.name || line.variant?.name || "Product";
      const amount = line.totalPrice?.gross?.amount?.toFixed(2) || "0.00";

      return {
        name: productName,
        quantity: line.quantity || 0,
        price: `${amount} ${currency}`,
      };
    });
  }

  /**
   * Format money amount with currency
   */
  static formatMoney(amount: number | undefined, currency: string): string {
    const value = amount?.toFixed(2) || "0.00";
    return `${value} ${currency}`;
  }

  /**
   * Format order date for display
   */
  static formatOrderDate(order: SaleorOrder, languageCode: LanguageCode): string {
    const date = order.created ? new Date(order.created) : new Date();
    const locale = localeConfigs[languageCode] || localeConfigs[DEFAULT_LANGUAGE];
    return date.toLocaleString(locale);
  }

  /**
   * Get language code with fallback
   */
  static getLanguageCode(order: SaleorOrder): LanguageCode {
    const lang = order.languageCode?.toLowerCase() as LanguageCode;
    if (["en", "sr", "de", "fr"].includes(lang)) {
      return lang;
    }
    return DEFAULT_LANGUAGE;
  }

  /**
   * Transform order into email data structure
   */
  static transformToEmailData(
    order: SaleorOrder,
    translations: Record<string, any>
  ): EmailData {
    const languageCode = this.getLanguageCode(order);
    const currency = order.total?.gross?.currency || DEFAULT_CURRENCY;
    const customerName = this.extractCustomerName(order);
    const paymentMethod = PaymentMethodService.detectPaymentMethod(order);

    return {
      ...translations,
      orderNumber: order.number || order.id,
      customerName,
      greeting: "", // Will be compiled by email builder
      subject: "", // Will be compiled by email builder
      orderDate: this.formatOrderDate(order, languageCode),
      orderStatus: order.status || "unfulfilled",
      items: this.formatItems(order),
      subtotal: this.formatMoney(order.subtotal?.gross?.amount, currency),
      shipping: this.formatMoney(order.shippingPrice?.gross?.amount, currency),
      tax: this.formatMoney(order.total?.tax?.amount, currency),
      total: this.formatMoney(order.total?.gross?.amount, currency),
      shippingAddress: this.formatShippingAddress(order),
      phone: this.extractPhone(order),
      paymentMethod: PaymentMethodService.getPaymentLabel(paymentMethod),
      paymentLabel: "Payment:", // Can be moved to config if needed per language
    };
  }

  /**
   * Transform order into admin email data structure
   */
  static transformToAdminEmailData(
    order: SaleorOrder,
    translations: Record<string, any>,
    adminTranslations: Record<string, string>
  ): Record<string, any> {
    const baseData = this.transformToEmailData(order, translations);
    const paymentMethod = PaymentMethodService.detectPaymentMethod(order);

    return {
      ...baseData,
      ...adminTranslations,
      customerEmail: order.userEmail || "",
      paymentMethod: PaymentMethodService.getPaymentLabel(paymentMethod),
      paymentLabel: "Payment:",
    };
  }
}
