/**
 * Platform Adapters for Unified Data Format
 *
 * Converts platform-specific data structures (Shopify, WooCommerce, ShopRenter)
 * into unified formats for consistent API responses.
 *
 * Related: Issue #48 - GDPR-compliant webshop sync refactoring
 */

// ============================================================================
// Unified Data Interfaces
// ============================================================================

export interface UnifiedAddress {
  first_name?: string | null;
  last_name?: string | null;
  company?: string | null;
  address1?: string | null;
  address2?: string | null;
  city?: string | null;
  province?: string | null;
  province_code?: string | null;
  country?: string | null;
  country_code?: string | null;
  zip?: string | null;
  phone?: string | null;
}

export interface UnifiedCustomer {
  id: string;
  platform: "shopify" | "woocommerce" | "shoprenter";
  email: string | null;
  first_name: string | null;
  last_name: string | null;
  phone: string | null;
  orders_count: number;
  total_spent: number;
  currency: string;
  created_at: string | null;
  updated_at: string | null;
  addresses?: UnifiedAddress[];
  default_address?: UnifiedAddress | null;
  tags?: string[];
  note?: string | null;
  accepts_marketing?: boolean;
  state?: string; // Customer state (enabled, disabled, etc.)
  platform_specific: unknown; // Original platform data
}

export interface UnifiedLineItem {
  id: string;
  product_id?: string | null;
  variant_id?: string | null;
  name: string;
  sku?: string | null;
  quantity: number;
  price: number;
  total: number;
  tax?: number | null;
  image_url?: string | null;
}

export interface UnifiedOrder {
  id: string;
  platform: "shopify" | "woocommerce" | "shoprenter";
  order_number: string;
  name?: string | null; // Display name (e.g., "#1001")
  status: string;
  financial_status?: string | null;
  fulfillment_status?: string | null;
  total_price: number;
  subtotal_price?: number | null;
  total_tax?: number | null;
  currency: string;
  customer_name: string | null;
  customer_email: string | null;
  customer_phone?: string | null;
  line_items: UnifiedLineItem[];
  billing_address?: UnifiedAddress | null;
  shipping_address?: UnifiedAddress | null;
  note?: string | null;
  tags?: string[];
  created_at: string;
  updated_at: string | null;
  platform_specific: unknown; // Original platform data
}

export interface UnifiedProduct {
  id: string;
  platform: "shopify" | "woocommerce" | "shoprenter";
  title: string;
  description?: string | null;
  short_description?: string | null;
  sku?: string | null;
  price: number;
  compare_at_price?: number | null;
  currency: string;
  status: string;
  vendor?: string | null;
  product_type?: string | null;
  tags?: string[];
  images?: Array<{
    id?: string;
    src: string;
    alt?: string | null;
  }>;
  variants?: Array<{
    id: string;
    title?: string;
    sku?: string | null;
    price: number;
    inventory_quantity?: number | null;
  }>;
  inventory_quantity?: number | null;
  stock_status?: string | null;
  created_at?: string | null;
  updated_at?: string | null;
  platform_specific: unknown; // Original platform data
}

// ============================================================================
// Shopify Adapters
// ============================================================================

export function adaptShopifyCustomer(shopifyCustomer: any): UnifiedCustomer {
  return {
    id: String(shopifyCustomer.id),
    platform: "shopify",
    email: shopifyCustomer.email || null,
    first_name: shopifyCustomer.first_name || null,
    last_name: shopifyCustomer.last_name || null,
    phone: shopifyCustomer.phone || null,
    orders_count: shopifyCustomer.orders_count || 0,
    total_spent: parseFloat(shopifyCustomer.total_spent || "0"),
    currency: shopifyCustomer.currency || "USD",
    created_at: shopifyCustomer.created_at || null,
    updated_at: shopifyCustomer.updated_at || null,
    addresses: shopifyCustomer.addresses?.map((addr: any) => adaptShopifyAddress(addr)) || [],
    default_address: shopifyCustomer.default_address
      ? adaptShopifyAddress(shopifyCustomer.default_address)
      : null,
    tags: shopifyCustomer.tags ? shopifyCustomer.tags.split(",").map((t: string) => t.trim()) : [],
    note: shopifyCustomer.note || null,
    accepts_marketing: shopifyCustomer.accepts_marketing || false,
    state: shopifyCustomer.state || "enabled",
    platform_specific: shopifyCustomer,
  };
}

export function adaptShopifyAddress(shopifyAddress: any): UnifiedAddress {
  return {
    first_name: shopifyAddress.first_name || null,
    last_name: shopifyAddress.last_name || null,
    company: shopifyAddress.company || null,
    address1: shopifyAddress.address1 || null,
    address2: shopifyAddress.address2 || null,
    city: shopifyAddress.city || null,
    province: shopifyAddress.province || null,
    province_code: shopifyAddress.province_code || null,
    country: shopifyAddress.country || null,
    country_code: shopifyAddress.country_code || null,
    zip: shopifyAddress.zip || null,
    phone: shopifyAddress.phone || null,
  };
}

export function adaptShopifyOrder(shopifyOrder: any): UnifiedOrder {
  return {
    id: String(shopifyOrder.id),
    platform: "shopify",
    order_number: String(shopifyOrder.order_number || shopifyOrder.id),
    name: shopifyOrder.name || null,
    status: shopifyOrder.financial_status || "pending",
    financial_status: shopifyOrder.financial_status || null,
    fulfillment_status: shopifyOrder.fulfillment_status || null,
    total_price: parseFloat(shopifyOrder.total_price || "0"),
    subtotal_price: parseFloat(shopifyOrder.subtotal_price || "0"),
    total_tax: parseFloat(shopifyOrder.total_tax || "0"),
    currency: shopifyOrder.currency || "USD",
    customer_name: shopifyOrder.customer
      ? `${shopifyOrder.customer.first_name || ""} ${shopifyOrder.customer.last_name || ""}`.trim()
      : null,
    customer_email: shopifyOrder.customer?.email || shopifyOrder.email || null,
    customer_phone: shopifyOrder.customer?.phone || shopifyOrder.phone || null,
    line_items: shopifyOrder.line_items?.map((item: any) => adaptShopifyLineItem(item)) || [],
    billing_address: shopifyOrder.billing_address
      ? adaptShopifyAddress(shopifyOrder.billing_address)
      : null,
    shipping_address: shopifyOrder.shipping_address
      ? adaptShopifyAddress(shopifyOrder.shipping_address)
      : null,
    note: shopifyOrder.note || null,
    tags: shopifyOrder.tags ? shopifyOrder.tags.split(",").map((t: string) => t.trim()) : [],
    created_at: shopifyOrder.created_at || new Date().toISOString(),
    updated_at: shopifyOrder.updated_at || null,
    platform_specific: shopifyOrder,
  };
}

export function adaptShopifyLineItem(shopifyItem: any): UnifiedLineItem {
  return {
    id: String(shopifyItem.id),
    product_id: shopifyItem.product_id ? String(shopifyItem.product_id) : null,
    variant_id: shopifyItem.variant_id ? String(shopifyItem.variant_id) : null,
    name: shopifyItem.name || shopifyItem.title || "Unknown Product",
    sku: shopifyItem.sku || null,
    quantity: shopifyItem.quantity || 1,
    price: parseFloat(shopifyItem.price || "0"),
    total: parseFloat(shopifyItem.price || "0") * (shopifyItem.quantity || 1),
    tax: parseFloat(shopifyItem.total_tax || "0"),
  };
}

export function adaptShopifyProduct(shopifyProduct: any): UnifiedProduct {
  const firstVariant = shopifyProduct.variants?.[0];

  return {
    id: String(shopifyProduct.id),
    platform: "shopify",
    title: shopifyProduct.title || "Untitled Product",
    description: shopifyProduct.body_html || null,
    sku: firstVariant?.sku || null,
    price: parseFloat(firstVariant?.price || "0"),
    compare_at_price: firstVariant?.compare_at_price
      ? parseFloat(firstVariant.compare_at_price)
      : null,
    currency: "USD", // Shopify doesn't include currency in product data
    status: shopifyProduct.status || "active",
    vendor: shopifyProduct.vendor || null,
    product_type: shopifyProduct.product_type || null,
    tags: shopifyProduct.tags ? shopifyProduct.tags.split(",").map((t: string) => t.trim()) : [],
    images: shopifyProduct.images?.map((img: any) => ({
      id: String(img.id),
      src: img.src,
      alt: img.alt || null,
    })) || [],
    variants: shopifyProduct.variants?.map((v: any) => ({
      id: String(v.id),
      title: v.title,
      sku: v.sku || null,
      price: parseFloat(v.price || "0"),
      inventory_quantity: v.inventory_quantity || 0,
    })) || [],
    inventory_quantity: firstVariant?.inventory_quantity || 0,
    created_at: shopifyProduct.created_at || null,
    updated_at: shopifyProduct.updated_at || null,
    platform_specific: shopifyProduct,
  };
}

// ============================================================================
// WooCommerce Adapters
// ============================================================================

export function adaptWooCommerceCustomer(wcCustomer: any): UnifiedCustomer {
  return {
    id: String(wcCustomer.id),
    platform: "woocommerce",
    email: wcCustomer.email || null,
    first_name: wcCustomer.first_name || null,
    last_name: wcCustomer.last_name || null,
    phone: wcCustomer.billing?.phone || null,
    orders_count: wcCustomer.orders_count || 0,
    total_spent: parseFloat(wcCustomer.total_spent || "0"),
    currency: "USD", // WooCommerce doesn't include currency in customer data
    created_at: wcCustomer.date_created || null,
    updated_at: wcCustomer.date_modified || null,
    addresses: [
      wcCustomer.billing ? adaptWooCommerceAddress(wcCustomer.billing) : null,
      wcCustomer.shipping ? adaptWooCommerceAddress(wcCustomer.shipping) : null,
    ].filter(Boolean) as UnifiedAddress[],
    default_address: wcCustomer.billing ? adaptWooCommerceAddress(wcCustomer.billing) : null,
    note: null,
    accepts_marketing: false,
    platform_specific: wcCustomer,
  };
}

export function adaptWooCommerceAddress(wcAddress: any): UnifiedAddress {
  return {
    first_name: wcAddress.first_name || null,
    last_name: wcAddress.last_name || null,
    company: wcAddress.company || null,
    address1: wcAddress.address_1 || null,
    address2: wcAddress.address_2 || null,
    city: wcAddress.city || null,
    province: wcAddress.state || null,
    country: wcAddress.country || null,
    zip: wcAddress.postcode || null,
    phone: wcAddress.phone || null,
  };
}

export function adaptWooCommerceOrder(wcOrder: any): UnifiedOrder {
  return {
    id: String(wcOrder.id),
    platform: "woocommerce",
    order_number: String(wcOrder.number || wcOrder.id),
    status: wcOrder.status || "pending",
    total_price: parseFloat(wcOrder.total || "0"),
    subtotal_price: parseFloat(wcOrder.line_items?.reduce((sum: number, item: any) =>
      sum + parseFloat(item.subtotal || "0"), 0) || "0"),
    total_tax: parseFloat(wcOrder.total_tax || "0"),
    currency: wcOrder.currency || "USD",
    customer_name: `${wcOrder.billing?.first_name || ""} ${wcOrder.billing?.last_name || ""}`.trim() || null,
    customer_email: wcOrder.billing?.email || null,
    customer_phone: wcOrder.billing?.phone || null,
    line_items: wcOrder.line_items?.map((item: any) => adaptWooCommerceLineItem(item)) || [],
    billing_address: wcOrder.billing ? adaptWooCommerceAddress(wcOrder.billing) : null,
    shipping_address: wcOrder.shipping ? adaptWooCommerceAddress(wcOrder.shipping) : null,
    note: wcOrder.customer_note || null,
    created_at: wcOrder.date_created || new Date().toISOString(),
    updated_at: wcOrder.date_modified || null,
    platform_specific: wcOrder,
  };
}

export function adaptWooCommerceLineItem(wcItem: any): UnifiedLineItem {
  return {
    id: String(wcItem.id),
    product_id: wcItem.product_id ? String(wcItem.product_id) : null,
    variant_id: wcItem.variation_id ? String(wcItem.variation_id) : null,
    name: wcItem.name || "Unknown Product",
    sku: wcItem.sku || null,
    quantity: wcItem.quantity || 1,
    price: parseFloat(wcItem.price || "0"),
    total: parseFloat(wcItem.total || "0"),
    tax: parseFloat(wcItem.total_tax || "0"),
    image_url: wcItem.image?.src || null,
  };
}

export function adaptWooCommerceProduct(wcProduct: any): UnifiedProduct {
  return {
    id: String(wcProduct.id),
    platform: "woocommerce",
    title: wcProduct.name || "Untitled Product",
    description: wcProduct.description || null,
    short_description: wcProduct.short_description || null,
    sku: wcProduct.sku || null,
    price: parseFloat(wcProduct.price || "0"),
    compare_at_price: wcProduct.regular_price ? parseFloat(wcProduct.regular_price) : null,
    currency: "USD", // WooCommerce doesn't include currency in product data
    status: wcProduct.status || "publish",
    product_type: wcProduct.type || null,
    tags: wcProduct.tags?.map((tag: any) => tag.name) || [],
    images: wcProduct.images?.map((img: any) => ({
      id: String(img.id),
      src: img.src,
      alt: img.alt || null,
    })) || [],
    variants: wcProduct.variations ? [] : undefined, // WooCommerce requires separate API call for variations
    inventory_quantity: wcProduct.stock_quantity || 0,
    stock_status: wcProduct.stock_status || "instock",
    created_at: wcProduct.date_created || null,
    updated_at: wcProduct.date_modified || null,
    platform_specific: wcProduct,
  };
}

// ============================================================================
// ShopRenter Adapters
// ============================================================================

export function adaptShopRenterCustomer(srCustomer: any): UnifiedCustomer {
  return {
    id: String(srCustomer.id),
    platform: "shoprenter",
    email: srCustomer.email || null,
    first_name: srCustomer.firstname || null,
    last_name: srCustomer.lastname || null,
    phone: srCustomer.phone || null,
    orders_count: 0, // ShopRenter doesn't provide this in customer data
    total_spent: 0, // Would need to calculate from orders
    currency: "HUF", // ShopRenter default currency
    created_at: srCustomer.dateCreated || null,
    updated_at: srCustomer.dateUpdated || null,
    note: null,
    accepts_marketing: srCustomer.newsletter === "1",
    platform_specific: srCustomer,
  };
}

export function adaptShopRenterOrder(srOrder: any): UnifiedOrder {
  return {
    id: String(srOrder.id),
    platform: "shoprenter",
    order_number: String(srOrder.innerId || srOrder.id),
    status: srOrder.orderStatus?.name || "pending",
    total_price: parseFloat(srOrder.totalGross || "0"),
    subtotal_price: parseFloat(srOrder.totalNet || "0"),
    total_tax: parseFloat(srOrder.totalGross || "0") - parseFloat(srOrder.totalNet || "0"),
    currency: srOrder.currency || "HUF",
    customer_name: `${srOrder.firstname || ""} ${srOrder.lastname || ""}`.trim() || null,
    customer_email: srOrder.email || null,
    customer_phone: srOrder.phone || null,
    line_items: srOrder.orderProducts?.map((item: any) => adaptShopRenterLineItem(item)) || [],
    billing_address: srOrder.invoiceAddress ? {
      first_name: srOrder.invoiceAddress.firstname || null,
      last_name: srOrder.invoiceAddress.lastname || null,
      company: srOrder.invoiceAddress.company || null,
      address1: srOrder.invoiceAddress.address || null,
      city: srOrder.invoiceAddress.city || null,
      zip: srOrder.invoiceAddress.zip || null,
      phone: srOrder.invoiceAddress.phone || null,
      country: srOrder.invoiceAddress.country?.name || null,
    } : null,
    shipping_address: srOrder.shippingAddress ? {
      first_name: srOrder.shippingAddress.firstname || null,
      last_name: srOrder.shippingAddress.lastname || null,
      company: srOrder.shippingAddress.company || null,
      address1: srOrder.shippingAddress.address || null,
      city: srOrder.shippingAddress.city || null,
      zip: srOrder.shippingAddress.zip || null,
      phone: srOrder.shippingAddress.phone || null,
      country: srOrder.shippingAddress.country?.name || null,
    } : null,
    note: srOrder.customerComment || null,
    created_at: srOrder.dateCreated || new Date().toISOString(),
    updated_at: srOrder.dateUpdated || null,
    platform_specific: srOrder,
  };
}

export function adaptShopRenterLineItem(srItem: any): UnifiedLineItem {
  return {
    id: String(srItem.id),
    product_id: srItem.product?.id ? String(srItem.product.id) : null,
    name: srItem.name || srItem.product?.name || "Unknown Product",
    sku: srItem.product?.sku || null,
    quantity: parseInt(srItem.quantity || "1"),
    price: parseFloat(srItem.price || "0"),
    total: parseFloat(srItem.price || "0") * parseInt(srItem.quantity || "1"),
  };
}

export function adaptShopRenterProduct(srProduct: any): UnifiedProduct {
  return {
    id: String(srProduct.innerId || srProduct.id),
    platform: "shoprenter",
    title: srProduct.name || "Untitled Product",
    description: srProduct.description || null,
    sku: srProduct.sku || null,
    price: parseFloat(srProduct.price || "0"),
    currency: "HUF",
    status: srProduct.status === "1" ? "active" : "inactive",
    tags: [],
    images: srProduct.productImages?.map((img: any) => ({
      id: String(img.id),
      src: img.imageUrl,
    })) || [],
    inventory_quantity: parseInt(srProduct.stock || "0"),
    created_at: srProduct.dateCreated || null,
    updated_at: srProduct.dateUpdated || null,
    platform_specific: srProduct,
  };
}

// ============================================================================
// Helper Functions
// ============================================================================

/**
 * Get adapter functions for a specific platform
 */
export function getAdapters(platform: string) {
  switch (platform.toLowerCase()) {
    case "shopify":
      return {
        customer: adaptShopifyCustomer,
        order: adaptShopifyOrder,
        product: adaptShopifyProduct,
      };
    case "woocommerce":
      return {
        customer: adaptWooCommerceCustomer,
        order: adaptWooCommerceOrder,
        product: adaptWooCommerceProduct,
      };
    case "shoprenter":
      return {
        customer: adaptShopRenterCustomer,
        order: adaptShopRenterOrder,
        product: adaptShopRenterProduct,
      };
    default:
      throw new Error(`Unsupported platform: ${platform}`);
  }
}
