<?php

namespace NewsletterBridge\Services\ImgCDN;

use NewsletterBridge\Config\CdnConfig;

class CDNFactory {

    public const IMG_PROXY_PLAIN = 'imgproxy_plain';
    public const IMG_PROXY_ENC   = 'imgproxy_enc';
    public const THUMBOR         = 'thumbor';
    public const LOCAL           = 'local';

    /**
     * Ritorna l'implementazione CDN configurata.
     */
    public static function getCDN(?string $type = null): CDN {
        $config = CdnConfig::getConfig();
        $selectedType = $type ?: ($config->provider ?? self::LOCAL);
        if (empty($selectedType)) {
            $selectedType = self::LOCAL;
        }

        // In ambiente locale forziamo la modalità local per evitare chiamate esterne
        if (defined('WP_ENV') && WP_ENV === 'local') {
            $selectedType = self::LOCAL;
        }

        switch ($selectedType) {
            case self::IMG_PROXY_PLAIN:
                return new ImgProxy(
                    $config->imgProxy->url ?? '',
                    $config->imgProxy->key ?? '',
                    $config->imgProxy->salt ?? ''
                );
            case self::IMG_PROXY_ENC:
                return new ImgProxyEnc(
                    $config->imgProxy->url ?? '',
                    $config->imgProxy->key ?? '',
                    $config->imgProxy->salt ?? ''
                );
            case self::THUMBOR:
                return new Thumbor(
                    $config->thumbor->url ?? '',
                    $config->thumbor->key ?? ''
                );
            case self::LOCAL:
                return new Local();
            default:
                return new Local();
        }
    }
}
