<?php

namespace Simplyin\Simplyin_W_Plugin\Payments\Mappers;

use Exception;
use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Model\Payment_Method;
use Simplyin\Simplyin_W_Plugin\Payments\View_Model\Classic_Checkout\Payment_Method_Item_Provider;
use Simplyin\Simplyin_W_Plugin\Lib\Remote\SimplyInApi\Model\PaymentsGetAvailablePaymentMethods200ResponseInner as AvailablePaymentMethod;

class Payment_Provider_Mapper {

	/**
	 * @var AvailablePaymentMethod[]
	 */
	private array $methods_deserialized;

	/**
	 * @param AvailablePaymentMethod[]
	 */
	public function __construct( array $raw_channels_from_simplyin_api ) {
		$this->methods_deserialized = $raw_channels_from_simplyin_api;
	}


	public function map(): Payment_Method_Item_Provider {

		if ( empty( $this->methods_deserialized ) ) {
			throw new Exception( "Empty payment methods list" );
		}

		$provider_ids = [];
		$provider_raw = null;

		foreach ( $this->methods_deserialized as $raw_channel ) {
			$provider_raw                           = $raw_channel->getPaymentProvider();
			$provider_ids[ $provider_raw->getId() ] = $provider_raw->getId();
		}

		if ( count( $provider_ids ) > 1 ) {
			throw new Exception( "Unsupported provider_groups qty" );
		}

		return new Payment_Method_Item_Provider(
			$provider_raw->getId(),
			$provider_raw->getName(),
			$provider_raw->getLogoUrl(),
			$provider_raw->getRegulationsUrl(),
			$provider_raw->getGdprUrl(),

		);
	}


	public static function deserialize( string $serialised
	): Payment_Method_Item_Provider {
		$data = unserialize( $serialised, [ 'allowed_classes' => [ Payment_Method_Item_Provider::class ] ] );

		return $data;
	}

	public static function serialize( Payment_Method_Item_Provider $provider
	): string {
		return serialize( $provider );
	}
}
