<?php

namespace App\Services\Oms;

use App\Models\Order;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class OmsClient
{
    public function syncOrder(Order $order): void
    {
        $order->loadMissing([
            'details',
            'orderTypeCatalog',
            'statusCatalog',
            'carrierCatalog',
            'province',
            'canton',
            'district',
        ]);

        $baseUrl = config('services.oms.base_url');
        if (blank($baseUrl)) {
            // Integración opcional: si no hay URL configurada, no hacemos nada.
            return;
        }

        $token = config('services.oms.token');

        $payload = [
            'order_reference' => $order->order_reference,
            'order_type' => $order->orderTypeCatalog?->code,
            'status' => $order->statusCatalog?->code,
            'carrier' => $order->carrierCatalog?->code,
            'guide' => $order->guide,
            'date_order' => optional($order->date_order)->toIso8601String(),

            'customer' => [
                'codClient' => $order->codClient,
                'name' => $order->customer_name,
                'email' => $order->customer_email,
                'phone' => $order->customer_phone,
            ],

            'address' => [
                'province' => $order->province?->name,
                'canton' => $order->canton?->name,
                'district' => $order->district?->name,
                'postal_code' => $order->postal_code,
                'detail' => $order->address_detail,
            ],

            'totals' => [
                'total_productsTI' => $order->total_productsTI,
                'total_productsTE' => $order->total_productsTE,
                'total_shipping' => $order->total_shipping,
                'total_discounts' => $order->total_discounts,
                'total_paidTI' => $order->total_paidTI,
                'total_paidTE' => $order->total_paidTE,
            ],

            'details' => $order->details->map(fn ($d) => [
                'product_reference' => $d->product_reference,
                'product_name' => $d->product_name,
                'product_quantity' => $d->product_quantity,
                'product_tax' => $d->product_tax,
                'product_priceTI' => $d->product_priceTI,
                'product_priceTE' => $d->product_priceTE,
                'total_priceTI' => $d->total_priceTI,
                'total_priceTE' => $d->total_priceTE,
            ])->all(),
        ];

        try {
            $request = Http::baseUrl(rtrim($baseUrl, '/'))
                ->timeout(10)
                ->acceptJson();

            if (! blank($token)) {
                $request = $request->withToken($token);
            }

            $response = $request->post('/api/orders/sync', $payload);

            if ($response->failed()) {
                Log::warning('OMS sync failed', [
                    'order_reference' => $order->order_reference,
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);

                $response->throw();
            }
        } catch (ConnectionException $e) {
            // Permite que el Job reintente.
            throw $e;
        }
    }
}
