<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ShippoService
{
    protected $apiKey;
    
    public function __construct()
    {
        $this->apiKey = config('services.shippo.key');
    }
    
    /**
     * Calculate shipping for checkout
     * 
     * @param array $address
     * @param float $weight
     * @param float $amount
     * @return array
     */
    public function calculateShipping($address, $weight = 1.0, $amount = 0.0)
    {
        try {
            Log::info('Calculating shipping for checkout', [
                'address' => $address,
                'weight' => $weight,
                'amount' => $amount
            ]);
            
            // Use dummy data in test mode
            if (config('services.shippo.use_dummy_data', true)) {
                return $this->getDummyRates();
            }
            
            $fromAddress = [
                'name' => 'Aphrodaily Store',
                'street1' => '123 Main Street',
                'city' => 'Los Angeles',
                'state' => 'CA',
                'zip' => '90001',
                'country' => 'US',
            ];
            
            $toAddress = [
                'name' => $address['name'] ?? 'Customer',
                'street1' => $address['street1'],
                'city' => $address['city'],
                'state' => $address['state'],
                'zip' => $address['zip'],
                'country' => $address['country'] ?? 'US',
            ];
            
            $parcel = [
                'length' => '10',
                'width' => '10',
                'height' => '10',
                'distance_unit' => 'in',
                'weight' => (string) $weight,
                'mass_unit' => 'lb',
            ];
            
            return $this->getRates($fromAddress, $toAddress, $parcel);
            
        } catch (\Exception $e) {
            Log::error('Error calculating shipping for checkout:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return [
                'success' => false,
                'message' => 'Error calculating shipping: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Create a shipment and get rates
     * 
     * @param array $fromAddress
     * @param array $toAddress
     * @param array $parcel
     * @return array
     */
    public function getRates($fromAddress, $toAddress, $parcel)
    {
        try {
            Log::info('Shippo getRates called with:', [
                'from' => $fromAddress,
                'to' => $toAddress,
                'parcel' => $parcel
            ]);
            
            $response = Http::withHeaders([
                'Authorization' => 'ShippoToken ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ])->post('https://api.goshippo.com/shipments/', [
                'address_from' => $fromAddress,
                'address_to' => $toAddress,
                'parcels' => [$parcel],
                'async' => false
            ]);
            
            if (!$response->successful()) {
                Log::error('Shippo API Error:', ['response' => $response->body()]);
                return [
                    'success' => false,
                    'message' => 'Failed to get shipping rates: ' . $response->body()
                ];
            }
            
            $shipment = $response->json();
            
            if (empty($shipment['rates'])) {
                return [
                    'success' => false,
                    'message' => 'No shipping rates available'
                ];
            }
            
            return [
                'success' => true,
                'rates' => collect($shipment['rates'])->map(function($rate) {
                    return [
                        'service' => $rate['servicelevel']['token'],
                        'service_name' => $rate['servicelevel']['name'],
                        'amount' => number_format((float)$rate['amount'], 2),
                        'days' => $rate['estimated_days'] ?? 'Unknown'
                    ];
                })->values()->toArray()
            ];
            
        } catch (\Exception $e) {
            Log::error('Shippo service error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return [
                'success' => false,
                'message' => 'Error calculating shipping rates: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Get dummy shipping rates for testing
     * 
     * @return array
     */
    public function getDummyRates()
    {
        Log::info('Returning dummy shipping rates');
        return [
            'success' => true,
            'rates' => [
                [
                    'service' => 'usps_priority',
                    'service_name' => 'USPS Priority Mail',
                    'amount' => '7.99',
                    'days' => '1-3'
                ],
                [
                    'service' => 'usps_first',
                    'service_name' => 'USPS First Class Mail',
                    'amount' => '4.99',
                    'days' => '3-5'
                ],
                [
                    'service' => 'ups_ground',
                    'service_name' => 'UPS Ground',
                    'amount' => '8.99',
                    'days' => '1-5'
                ],
                [
                    'service' => 'fedex_express',
                    'service_name' => 'FedEx Express',
                    'amount' => '12.99',
                    'days' => '1-2'
                ]
            ]
        ];
    }
}