<?php

namespace SplitPay\Core;

use SplitPay\Contracts\IntegrationInterface;
use SplitPay\Contracts\GatewayAdapterInterface;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class IntegrationRegistry {

	private static ?self $instance = null;

	/** @var IntegrationInterface[] */
	private array $integrations = [];

	private function __construct() {}

	public static function getInstance(): self {
		if ( self::$instance === null ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	public function register( IntegrationInterface $integration ): void {
		$this->integrations[ $integration->getId() ] = $integration;
	}

	/** @return IntegrationInterface[] */
	public function getAll(): array {
		return $this->integrations;
	}

	/** @return IntegrationInterface[] */
	public function getActive(): array {
		return array_filter(
			$this->integrations,
			fn( IntegrationInterface $i ) => $i->isActive()
		);
	}

	public function getById( string $id ): ?IntegrationInterface {
		return $this->integrations[ $id ] ?? null;
	}

	/** @return GatewayAdapterInterface[] */
	public function getActiveGateways(): array {
		$gateways = [];

		foreach ( $this->getActive() as $integration ) {
			foreach ( $integration->getGatewayAdapters() as $gateway ) {
				$gateways[] = $gateway;
			}
		}

		return $gateways;
	}
}
