<?php

namespace App\Services;

use App\Data\AmadastCities;
use App\Models\Order;
use App\Models\ProductVariant;
use App\Models\Setting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class AmadastService
{
    private const ORDERS_URL  = 'https://shop-integration.amadast.com/v1/orders';
    private const CLIENT_ID   = 5;

    public static function submitOrder(Order $order): array
    {
        if (!Setting::get('amadast_enabled')) {
            return ['success' => false, 'message' => 'سرویس آمادست غیرفعال است.'];
        }

        $token     = Setting::get('amadast_access_token');
        $expiresAt = (int) Setting::get('amadast_token_expires_at', 0);
        if (!$token || $expiresAt <= now()->timestamp) {
            return ['success' => false, 'message' => 'توکن آمادست منقضی شده است.'];
        }

        $storeId = (int) Setting::get('amadast_store_id');
        if (!$storeId) {
            return ['success' => false, 'message' => 'فروشگاه آمادست در تنظیمات مشخص نشده است.'];
        }

        $order->loadMissing(['user', 'items']);

        $addr    = $order->address_snapshot ?? [];
        $cityId  = static::findCityId($addr['province'] ?? '', $addr['city'] ?? '');

        if (!$cityId) {
            return ['success' => false, 'message' => 'شناسه شهر مقصد در پایگاه داده آمادست یافت نشد.'];
        }

        // Load variants for weight and package_type
        $variantIds = $order->items->pluck('variant_id')->filter()->all();
        $variants   = ProductVariant::with('product')
            ->whereIn('id', $variantIds)
            ->get()
            ->keyBy('id');

        $defaultWeight = max(10, (int) Setting::get('amadast_default_weight', 500));
        $totalWeight   = 0;
        $packageType   = (int) Setting::get('amadast_default_pkg_type', 1);
        $productType   = 1;

        foreach ($order->items as $item) {
            $variant = $variants->get($item->variant_id);
            $w       = (int) ($variant?->weight ?? 0);
            $totalWeight += ($w > 0 ? $w : $defaultWeight) * $item->qty;

            if ($variant?->product?->package_type) {
                $packageType = (int) $variant->product->package_type;
            }
            if ($variant?->product?->amadast_product_type_id) {
                $productType = (int) $variant->product->amadast_product_type_id;
            }
        }

        $weight    = max(10, $totalWeight ?: $defaultWeight);
        $valueRial = max(10000, (int) round($order->total_amount * 10));

        $user            = $order->user;
        $recipientName   = trim(($user->first_name ?? '') . ' ' . ($user->last_name ?? '')) ?: 'مشتری';
        $recipientMobile = $user->mobile ?? '';
        $senderName      = Setting::get('amadast_sender_name') ?: config('app.name');
        $senderMobile    = preg_replace('/\s+/', '', trim(Setting::get('amadast_sender_mobile', '')));

        if (!$senderMobile) {
            return ['success' => false, 'message' => 'موبایل فرستنده در تنظیمات آمادست وارد نشده است.'];
        }

        $payload = [
            'store_id'              => $storeId,
            'external_order_id'     => $order->id,
            'recipient_name'        => $recipientName,
            'sender_name'           => $senderName,
            'recipient_mobile'      => $recipientMobile,
            'sender_mobile'         => $senderMobile,
            'recipient_city_id'     => $cityId,
            'recipient_address'     => $addr['address'] ?? '',
            'recipient_postal_code' => $addr['postal_code'] ?? '',
            'weight'                => $weight,
            'value'                 => $valueRial,
            'product_type'          => $productType,
            'package_type'          => $packageType,
        ];

        try {
            $response = Http::withHeaders([
                'Accept'        => 'application/json',
                'Content-Type'  => 'application/json',
                'X-Client-Code' => (string) self::CLIENT_ID,
                'Authorization' => 'Bearer ' . $token,
            ])->timeout(20)->post(self::ORDERS_URL, $payload);

            $body = $response->json();

            if ($response->successful() && ($body['success'] ?? false)) {
                $amadastId = $body['data']['id'] ?? null;
                if ($amadastId) {
                    $order->update(['amadast_order_id' => $amadastId]);
                }
                return ['success' => true, 'amadast_order_id' => $amadastId];
            }

            $msg = is_array($body['message'] ?? null)
                ? implode(' ', $body['message'])
                : ($body['message'] ?? 'HTTP ' . $response->status());

            Log::warning('Amadast order creation failed', [
                'order_id' => $order->id,
                'status'   => $response->status(),
                'body'     => $body,
            ]);

            return ['success' => false, 'message' => $msg];

        } catch (\Throwable $e) {
            Log::error('Amadast order creation exception', [
                'order_id' => $order->id,
                'error'    => $e->getMessage(),
            ]);
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    private static function findCityId(string $province, string $city): ?int
    {
        foreach (AmadastCities::allCitiesWithFullName() as $c) {
            if ($c['province'] === $province && $c['city_name'] === $city) {
                return (int) $c['id'];
            }
        }
        return null;
    }
}
