<?php

namespace App\Services\Carriers;

use App\Models\Carrier;
use InvalidArgumentException;

class CarrierServiceFactory
{
    /**
     * Create a carrier service instance based on carrier slug
     *
     * @param string $carrierSlug
     * @param array|null $config Optional config override
     * @return CarrierInterface
     * @throws InvalidArgumentException
     */
    public static function make(string $carrierSlug, ?array $config = null): CarrierInterface
    {
        // If config is not provided, load from database
        if ($config === null) {
            $carrier = Carrier::where('slug', $carrierSlug)->first();
            
            if (!$carrier) {
                throw new InvalidArgumentException("Carrier with slug '{$carrierSlug}' not found.");
            }

            if (!$carrier->enabled) {
                throw new InvalidArgumentException("Carrier '{$carrierSlug}' is disabled.");
            }

            $config = $carrier->getDecryptedApiKeys();
        }

        return match ($carrierSlug) {
            'delhivery' => new DelhiveryCarrier($config),
            'expressbees' => new ExpressBeesCarrier($config),
            'indiapost' => new IndiaPostCarrier($config),
            'ekart' => new EkartCarrier($config),
            default => throw new InvalidArgumentException("Unsupported carrier: {$carrierSlug}"),
        };
    }

    /**
     * Create carrier service from Carrier model
     *
     * @param Carrier $carrier
     * @return CarrierInterface
     */
    public static function makeFromModel(Carrier $carrier): CarrierInterface
    {
        return self::make($carrier->slug);
    }
}

