<?php

declare(strict_types=1);

namespace External\HannahBundle\SAP\Exception;

class SAPManyException extends SAPException
{
    private $exceptions = [];

    public function __construct(iterable $exceptions = [])
    {
        parent::__construct('Some exceptions occurred: ');

        foreach ($exceptions as $exception) {
            $this->add($exception);
        }
    }

    public function add(\Throwable $exception): self
    {
        $this->exceptions[] = $exception;
        $this->message .= PHP_EOL.$exception->getMessage();

        return $this;
    }

    public function getExceptions(): array
    {
        return $this->exceptions;
    }

    public function getExceptionWithCode(string $code): ?SAPErrorException
    {
        foreach ($this->getExceptions() as $e) {
            if ($e instanceof SAPErrorException) {
                if ($e->getSAPErrorCode() === $code) {
                    return $e;
                }
            }
        }

        return null;
    }

    public function hasExceptionWithCode(array $codes): bool
    {
        foreach ($this->getExceptions() as $e) {
            if ($e instanceof SAPErrorException) {
                if (in_array($e->getSAPErrorCode(), $codes)) {
                    return true;
                }
            }
        }

        return false;
    }
}
