<?php

namespace App\Services\Shipping;

use App\Models\Order;
use App\Services\Shipping\Dto\ShipmentResponse;
use App\Services\Shipping\Providers\CorreosCRShippingProvider;
use App\Services\Shipping\Providers\MoovinShippingProvider;
use App\Services\Shipping\Providers\ShippingProvider;

class ShippingService
{
    public function provider(): ShippingProvider
    {
        $provider = (string) config('shipping.provider', 'moovin');

        return match ($provider) {
            'correos_cr' => new CorreosCRShippingProvider(
                baseUrl: config('shipping.correos_cr.base_url'),
                username: config('shipping.correos_cr.username'),
                password: config('shipping.correos_cr.password'),
                contract: config('shipping.correos_cr.contract'),
            ),
            default => new MoovinShippingProvider(
                baseUrl: config('shipping.moovin.base_url'),
                apiKey: config('shipping.moovin.api_key'),
                account: config('shipping.moovin.account'),
            ),
        };
    }

    public function ensureShipmentCreated(Order $order): ?ShipmentResponse
    {
        if (filled($order->guide)) {
            return null;
        }

        $provider = $this->provider();
        $response = $provider->createShipment($order);

        $order->forceFill([
            'guide' => $response->guideNumber,
        ])->save();

        $order->statusLogs()->create([
            'status' => $order->statusCatalog?->code ?? 'shipping',
            'note' => 'Guía generada por integración: '.$provider->name().' ('.$response->guideNumber.')',
            'happened_at' => now(),
        ]);

        return $response;
    }
}
