<?php

declare( strict_types=1 );

namespace Simplyin\Simplyin_W_Plugin\Shipping_Mapping\Integration\Furgonetka;

use Furgonetka_Map;
use Simplyin\Simplyin_W_Plugin\Shipping_Mapping\Integration\Abstract_Integration_Factory;
use Simplyin\Simplyin_W_Plugin\Shipping_Mapping\Integration\Integration_Factory_Interface;
use Simplyin\Simplyin_W_Plugin\Shipping_Mapping\Integration\Integration_Interface;
use WC_Shipping_Method;

class Furgonetka_Integration_Factory extends Abstract_Integration_Factory implements Integration_Factory_Interface {

	public function create( WC_Shipping_Method $method ): ?Integration_Interface {

		if ( ! class_exists( 'Furgonetka_Map' ) ) {
			return null;
		}

		$map     = Furgonetka_Map::get_configuration();
		$rate_id = $method->get_rate_id();
		$raw     = $map[ $rate_id ] ?? null;

		$provider = $this->resolve_provider( $raw );

		if ( ! $provider ) {
			return null;
		}

		$method_id = $this->get_method_id_by_rate_id( $rate_id );

		return $this->create_integration_by_method_id(
			$method_id,
			$method->get_instance_id(),
			$method->get_title(),
			$provider
		);
	}

	public function create_integration_by_method_id(
		string $method_id,
		int $instance_id,
		string $title,
		?string $provider = null
	): ?Integration_Interface {

		$full_title = sprintf(
			'%s (%s - %s)',
			$title,
			__( 'Furgonetka', 'simplyin' ),
			$provider
		);

		return new Furgonetka_Integration(
			$method_id,
			$instance_id,
			$full_title,
			$provider
		);
	}

	private function resolve_provider( $raw ): ?string {

		// Furgonetka Version <= 1.7.6
		if ( is_string( $raw ) && $raw !== '' ) {
			return $raw;
		}

		// Furgonetka Version >= 1.8.0
		if ( is_array( $raw ) ) {
			$provider = $raw['courier_service'] ?? null;

			if ( is_string( $provider ) && $provider !== '' ) {
				return $provider;
			}
		}

		return null;
	}
}
