<?php

namespace Fitsmart\PaypalParcels;

use Fitsmart\PaypalParcels\Application\TrackingHandlerFactory;
use Fitsmart\PaypalParcels\Contract\TrackingHandlerInterface;
use Fitsmart\PaypalParcels\Enum\ExternalServiceEnum;

class Plugin
{
    public const LOG_FILE_NAME = 'paypal_parcels_registration.log';

    public function __construct(
        /** @var TrackingHandlerInterface[] */
        public readonly array $trackingHandlers
    ) {
    }

    public static function bootstrap(): void
    {
        $serviceString = Config::getEnv('PP_EXTERNAL_SERVICE') ?? '';
        $services = array_unique(array_filter(array_map('trim', explode('|', $serviceString))));

        $handlers = [];

        foreach ($services as $service) {
            $serviceEnum = ExternalServiceEnum::tryFrom($service);
            if (is_null($serviceEnum)) {
                continue;
            }
            $handlers[] = TrackingHandlerFactory::make($serviceEnum->value);
        }

        $plugin = new self($handlers);

        $plugin->register_hooks();
    }

    public function register_hooks(): void
    {
        add_action('woocommerce_order_note_added', [$this, 'run_tracking_handler'], 10, 2);
    }


    public function run_tracking_handler(int $noteId, \WC_Order $order): void
    {
        foreach ($this->trackingHandlers as $handler) {
            $handler->process($noteId, $order);
        }
    }


}
