<?php
/**
 * Caterpoint Data Normalizer
 * 
 * Transforms Caterpoint order data into Magento-compatible format
 * for integration with ahs-magento\models\Carts::NewMagentoOrder()
 *
 * @category    PortalPeople
 * @package     Caterpoint
 */

namespace PortalPeople\caterpoint\components;

/**
 * Normalize Caterpoint orders to Magento format
 */
class DataNormalizer
{
    /**
     * Transform Caterpoint order response to Magento import format
     * 
     * Converts fetch-raw response data into format expected by:
     *   PortalPeople\magento\models\Carts::NewMagentoOrder($data)
     * 
     * @param array $caterpointOrder Raw Caterpoint order from fetch-raw response
     * @return array Magento-compatible order format
     */
    public static function normalizeOrder(array $caterpointOrder): array
    {
        $orderId = $caterpointOrder['orderIdentification']['entityIdentification'] ?? 'unknown';
        $createdAt = $caterpointOrder['creationDateTime'] ?? date('c');
        
        // Extract buyer details
        $buyerName = $caterpointOrder['buyer']['organisationDetails']['organisationName'] ?? 'Guest Customer';
        $nameParts = explode(' ', trim($buyerName), 2);
        $firstName = $nameParts[0] ?? 'Guest';
        $lastName = $nameParts[1] ?? 'Customer';
        
        // Extract delivery date
        $deliveryDate = $caterpointOrder['orderLogisticalInformation']['orderLogisticalDateInformation']['requestedDeliveryDateTime']['date'] ?? null;
        
        // Extract ship-to location
        $shipToId = $caterpointOrder['orderLogisticalInformation']['shipTo']['additionalPartyIdentification'] ?? '';
        
        // Transform order line items
        $lineItems = [];
        $totalPrice = 0;
        $totalDiscount = 0;
        
        if (!empty($caterpointOrder['orderLineItem']) && is_array($caterpointOrder['orderLineItem'])) {
            foreach ($caterpointOrder['orderLineItem'] as $lineItem) {
                $item = [
                    'sku' => $lineItem['transactionalTradeItem']['additionalTradeItemIdentification'] ?? 
                             $lineItem['transactionalTradeItem']['gtin'] ?? '',
                    'name' => $lineItem['transactionalTradeItem']['tradeItemDescription'] ?? 'Item',
                    'qty_ordered' => (int) ($lineItem['requestedQuantity'] ?? 1),
                    'row_total_incl_tax' => 0, // Caterpoint doesn't provide pricing in fetch-raw
                    'discount_amount' => 0,
                ];
                $lineItems[] = $item;
            }
        }
        
        // Build Magento-compatible order structure
        return [
            'payment' => [
                'method' => 'caterpoint_order', // Custom payment method identifier
            ],
            'order' => [
                'updated_at' => $createdAt,
                'id' => $orderId,
                'grand_total' => 0, // Caterpoint API doesn't provide pricing in fetch-raw
            ],
            'customer' => [
                'email' => "supplier-{$orderId}@caterpoint.local", // Placeholder email
                'firstname' => $firstName,
                'lastname' => $lastName,
            ],
            'billing_address' => [
                'street' => "Ship-To Location: {$shipToId}",
                'city' => 'Unknown',
                'postcode' => '',
                'telephone' => '',
            ],
            'shipping_address' => [
                'street' => "Ship-To Location: {$shipToId}",
                'city' => 'Unknown',
                'postcode' => '',
                'telephone' => '',
            ],
            'items' => $lineItems,
            'shipping_fields' => [
                'shipping_date' => $deliveryDate,
                'shipping_message' => 'Caterpoint Order Import',
            ],
            'shipping_method' => [
                'description' => 'Caterpoint Delivery',
            ],
            'order_source' => 'caterpoint',
            'sourceFormat' => 'caterpoint-xml',
            // Include original data for reference
            '_original' => $caterpointOrder,
        ];
    }
    
    /**
     * Transform multiple orders
     * 
     * @param array $orders Array of Caterpoint orders from fetch-raw
     * @return array Array of Magento-compatible orders
     */
    public static function normalizeOrders(array $orders): array
    {
        return array_map(fn($order) => self::normalizeOrder($order), $orders);
    }
    
    /**
     * Extract orders from fetch-raw response and normalize
     * 
     * @param array $fetchRawResponse Response from actionFetchRaw (with 'data' key)
     * @return array Array of normalized orders
     */
    public static function normalizeFromFetchRawResponse(array $fetchRawResponse): array
    {
        $orders = $fetchRawResponse['data']['orders'] ?? [];
        return self::normalizeOrders($orders);
    }
}
