<?php
namespace Core\App\Support;

use Core\App\Models\ShippingPriceModel;

class ShippingProviderPriceResolver
{
    public static function getMode(string $provider): string
    {
        $shipping = ShippingSettings::load();
        $mode = (string)($shipping['provider_price_modes'][$provider] ?? 'manual');
        return in_array($mode, ['manual', 'api', 'reference'], true) ? $mode : 'manual';
    }

    public static function getImportedPrice(string $provider, string $wilayaCode, string $deliveryType): ?float
    {
        $shipping = ShippingSettings::load();
        $wilayaCode = DzLocation::normalizeCode($wilayaCode);
        $deliveryType = $deliveryType === 'desk' ? 'desk' : 'home';
        $value = $shipping['provider_imported_prices'][$provider][$wilayaCode][$deliveryType] ?? null;
        return is_numeric($value) ? (float)$value : null;
    }

    public static function getManualPrice(string $provider, string $wilayaCode, string $deliveryType): ?float
    {
        $model = new ShippingPriceModel();
        $row = $model->getPrice($provider, DzLocation::normalizeCode($wilayaCode), $deliveryType === 'desk' ? 'desk' : 'home');
        return $row ? (float)$row['price'] : null;
    }

    public static function resolve(string $provider, string $wilayaCode, string $deliveryType): float
    {
        $mode = self::getMode($provider);
        $manual = self::getManualPrice($provider, $wilayaCode, $deliveryType);
        $imported = self::getImportedPrice($provider, $wilayaCode, $deliveryType);

        if ($mode === 'api') {
            if ($imported !== null) return $imported;
            if ($manual !== null) return $manual;
            return 0.0;
        }

        if ($manual !== null) return $manual;
        if ($mode === 'reference' && $imported !== null) return $imported;
        return 0.0;
    }
}
