<?php

namespace App\Services;

use App\Models\Order;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class DelhiveryService
{
    protected Client $client;

    public function __construct()
    {
        $this->client = new Client([
            'base_uri' => config('services.delhivery.api_url'),
            'timeout' => 30,
            'verify' => public_path('cacert.pem'),
        ]);
    }

    public function createShipment(Order $order): ?string
    {
        try {
            $address = $order->address_snapshot;

            $data = [
                'shipments' => [
                    [
                        'name' => $address['name'],
                        'add' => $address['line1'] . ' ' . ($address['line2'] ?? ''),
                        'pin' => $address['pin'],
                        'city' => $address['city'],
                        'state' => $address['state'],
                        'country' => 'India',
                        'phone' => $address['mobile'],
                        'order' => (string) $order->id,
                        'payment_mode' => 'Prepaid',
                        'return_pin' => config('services.delhivery.warehouse_pin'),
                        'return_city' => config('services.delhivery.city'),
                        'return_phone' => config('services.delhivery.phone'),
                        'return_add' => config('services.delhivery.address_line1'),
                        'return_state' => config('services.delhivery.state'),
                        'return_country' => 'India',
                        'products_desc' => $this->getProductsDescription($order),
                        'hsn_code' => '',
                        'cod_amount' => 0,
                        'order_date' => $order->placed_at ? $order->placed_at->format('Y-m-d H:i:s') : now()->format('Y-m-d H:i:s'),
                        'total_amount' => $order->total_payable,
                        'seller_add' => config('services.delhivery.address_line1'),
                        'seller_name' => config('services.delhivery.pickup_name'),
                        'seller_inv' => (string) $order->id,
                        'quantity' => $order->items->sum('qty'),
                        'waybill' => '',
                        'shipment_width' => 10,
                        'shipment_height' => 10,
                        'weight' => 500, // in grams
                        'seller_gst_tin' => '',
                        'shipping_mode' => 'Surface',
                        'address_type' => 'home',
                    ],
                ],
                'pickup_location' => [
                    'name' => config('services.delhivery.pickup_name'),
                ],
            ];

            $response = $this->client->post('/api/cmu/create.json', [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Token ' . config('services.delhivery.api_token'),
                ],
                'json' => $data,
                'form_params' => [
                    'format' => 'json',
                    'data' => json_encode($data),
                ],
            ]);

            $result = json_decode($response->getBody()->getContents(), true);

            if (isset($result['packages'][0]['waybill'])) {
                $awb = $result['packages'][0]['waybill'];

                Log::info('Delhivery shipment created', [
                    'order_id' => $order->id,
                    'awb' => $awb,
                ]);

                return $awb;
            }

            Log::error('Delhivery shipment creation failed', [
                'order_id' => $order->id,
                'response' => $result,
            ]);

            return null;
        } catch (\Exception $e) {
            Log::error('Delhivery shipment creation exception', [
                'order_id' => $order->id,
                'error' => $e->getMessage(),
            ]);

            return null;
        }
    }

    public function generateLabel(string $awb): ?string
    {
        try {
            // Delhivery label generation endpoint
            $labelUrl = config('services.delhivery.api_url') . '/api/p/packing_slip?wbns=' . $awb;

            Log::info('Delhivery label generated', [
                'awb' => $awb,
                'url' => $labelUrl,
            ]);

            return $labelUrl;
        } catch (\Exception $e) {
            Log::error('Delhivery label generation failed', [
                'awb' => $awb,
                'error' => $e->getMessage(),
            ]);

            return null;
        }
    }

    public function track(string $awb): ?array
    {
        try {
            $response = $this->client->get('/api/v1/packages/json/', [
                'headers' => [
                    'Authorization' => 'Token ' . config('services.delhivery.api_token'),
                ],
                'query' => [
                    'waybill' => $awb,
                ],
            ]);

            $result = json_decode($response->getBody()->getContents(), true);

            return $result['ShipmentData'][0] ?? null;
        } catch (\Exception $e) {
            Log::error('Delhivery tracking failed', [
                'awb' => $awb,
                'error' => $e->getMessage(),
            ]);

            return null;
        }
    }

    protected function getProductsDescription(Order $order): string
    {
        $items = $order->items->map(function ($item) {
            return $item->name . ' (x' . $item->qty . ')';
        })->take(3)->toArray();

        return implode(', ', $items);
    }
}
