<?php
namespace EasyChat\Library\Commerce;

use EasyChat\Library\Delivery\ShipmentTrackingService;

 
final class CommerceContextNormalizer
{
    private $tracking;

    public function __construct(?ShipmentTrackingService $tracking = null) { $this->tracking = $tracking; }

    public function orders(array $orders, string $provider, string $label, bool $ai_allowed, bool $force_tracking_refresh = false): array
    {
        $result = array();
        foreach (array_slice($orders, 0, 10) as $order) {
            if (!is_array($order) || trim((string)($order['id'] ?? '')) === '') continue;
            $items = array();
            foreach (array_slice((array)($order['items'] ?? array()), 0, 20) as $item) {
                $name = $this->plain($item['name'] ?? '', 180);
                if ($name === '') continue;
                $items[] = array(
                    'name' => $name, 'quantity' => max(1, (float)($item['quantity'] ?? 1)),
                    'product_id' => preg_replace('/[^A-Za-z0-9_.:-]/', '', (string)($item['product_id'] ?? '')),
                    'sku' => $this->plain($item['sku'] ?? '', 80),
                    'stock' => isset($item['stock']) && is_numeric($item['stock']) ? max(0, (float)$item['stock']) : null,
                );
            }
            $shipments = $this->tracking
                ? $this->tracking->enrich(
                    (array)($order['shipments'] ?? array()),
                    strtolower(trim((string)($order['fulfillment_status'] ?? $order['status'] ?? ''))),
                    $force_tracking_refresh
                )
                : array_slice((array)($order['shipments'] ?? array()), 0, 4);
            $url = $this->safeUrl((string)($order['url'] ?? ''));
            $normalized = array(
                'id' => preg_replace('/[^A-Za-z0-9_.:-]/', '', (string)$order['id']),
                'number' => $this->plain($order['number'] ?? $order['id'], 64),
                'date' => $this->plain($order['date'] ?? '', 40),
                'updated_at' => $this->plain($order['updated_at'] ?? $order['date'] ?? '', 40),
                'status' => $this->plain($order['status'] ?? '', 80),
                'total' => $this->plain($order['total'] ?? '', 64),
                 
                'payment' => $this->plain($order['payment'] ?? '', 100),
                'delivery' => $this->plain($order['delivery'] ?? '', 100),
                'payment_status' => $this->enum($order['payment_status'] ?? '', array('unknown','pending','paid','partially_paid','refunded','partially_refunded','failed')),
                'refund_status' => $this->enum($order['refund_status'] ?? '', array('none','requested','partial','full','unknown')),
                'fulfillment_status' => $this->enum($order['fulfillment_status'] ?? '', array('unknown','new','processing','ready','shipped','delivered','cancelled','returned')),
                'items' => $items, 'shipments' => $shipments,
                'source' => $provider, 'source_label' => $label, 'url' => $url,
                'provenance' => array('provider' => $provider, 'label' => $label, 'observed_at' => gmdate('c')),
            );
            $normalized['ai_facts'] = $ai_allowed ? $this->aiFacts($normalized) : array();
            $result[] = $normalized;
        }
        return $result;
    }

    private function aiFacts(array $order): array
    {
        $facts = array(
            array('key'=>'order_number','value'=>$order['number'],'source'=>$order['source_label'],'observed_at'=>$order['updated_at']),
            array('key'=>'order_status','value'=>$order['status'],'source'=>$order['source_label'],'observed_at'=>$order['updated_at']),
            array('key'=>'order_total','value'=>$order['total'],'source'=>$order['source_label'],'observed_at'=>$order['updated_at']),
        );
        foreach ((array)$order['shipments'] as $shipment) {
            if (($shipment['status_label'] ?? '') !== '') $facts[] = array('key'=>'shipment_status','value'=>$shipment['status_label'],'source'=>$shipment['carrier'] ?: $order['source_label'],'observed_at'=>$shipment['updated_at']);
            if (($shipment['eta'] ?? '') !== '') $facts[] = array('key'=>'shipment_eta','value'=>$shipment['eta'],'source'=>$shipment['carrier'] ?: $order['source_label'],'observed_at'=>$shipment['updated_at']);
        }
        return array_slice($facts, 0, 12);
    }

    private function safeUrl(string $url): string
    {
        $parts = parse_url($url);
        return is_array($parts) && strtolower((string)($parts['scheme'] ?? '')) === 'https' ? $url : '';
    }

    private function enum($value, array $allowed): string
    {
        $value = strtolower(trim((string)$value));
        return in_array($value, $allowed, true) ? $value : ($allowed[0] ?? '');
    }

    private function plain($value, int $limit): string
    {
        return mb_substr(trim(preg_replace('/\s+/u', ' ', strip_tags((string)$value))), 0, $limit, 'UTF-8');
    }
}
