<?php

namespace PortalPeople\magento\components;

class FieldMapper
{
    public static function normalizeOrder(array $rawOrder): array
    {
        $billing = $rawOrder['billing_address'] ?? [];
        $shipping = $rawOrder['shipping_address'] ?? [];
        $customer = $rawOrder['customer'] ?? [];
        $payment = $rawOrder['payment'] ?? [];
        $order = $rawOrder['order'] ?? $rawOrder;

        return [
            'orderNo' => (string) ($order['increment_id'] ?? $order['entity_id'] ?? $rawOrder['id'] ?? ''),
            'orderId' => (string) ($order['entity_id'] ?? $rawOrder['id'] ?? ''),
            'status' => (string) ($order['status'] ?? 'pending'),
            'orderDate' => (string) ($order['created_at'] ?? $order['updated_at'] ?? ''),
            'customerName' => trim((string) (($customer['firstname'] ?? '') . ' ' . ($customer['lastname'] ?? ''))),
            'customerEmail' => (string) ($customer['email'] ?? ''),
            'telephone' => (string) ($billing['telephone'] ?? $shipping['telephone'] ?? ''),
            'currency' => (string) ($order['base_currency_code'] ?? $order['order_currency_code'] ?? ''),
            'deliveryAddress' => [
                'line1' => (string) ($shipping['street'] ?? ''),
                'line2' => '',
                'city' => (string) ($shipping['city'] ?? ''),
                'postcode' => (string) ($shipping['postcode'] ?? ''),
                'country' => (string) ($shipping['country_id'] ?? ''),
            ],
            'billingAddress' => [
                'line1' => (string) ($billing['street'] ?? ''),
                'line2' => '',
                'city' => (string) ($billing['city'] ?? ''),
                'postcode' => (string) ($billing['postcode'] ?? ''),
                'country' => (string) ($billing['country_id'] ?? ''),
            ],
            'paymentMethod' => (string) ($payment['method'] ?? ''),
            'orderLines' => self::normalizeLines($rawOrder['items'] ?? []),
            '_raw' => $rawOrder,
        ];
    }

    private static function normalizeLines(array $items): array
    {
        $lines = [];
        foreach ($items as $index => $item) {
            if (!is_array($item)) {
                continue;
            }

            $lines[] = [
                'lineNo' => $index + 1,
                'sku' => (string) ($item['sku'] ?? ''),
                'productName' => (string) ($item['name'] ?? ''),
                'description' => (string) ($item['description'] ?? ''),
                'quantity' => (int) ($item['qty_ordered'] ?? $item['qty'] ?? 0),
                'unitPrice' => (float) ($item['base_price'] ?? $item['price'] ?? 0),
                'lineTotal' => (float) ($item['base_row_total_incl_tax'] ?? $item['row_total_incl_tax'] ?? 0),
                'data' => $item,
            ];
        }

        return $lines;
    }
}
