<?php

namespace Planaday\Utility\DataFilters;

use Exception;
use Throwable;

class InvalidFieldsException extends Exception {
	/** @var array<string, InvalidException|InvalidFieldsException> */
	protected array $invalidFields;

	/**
	 * @param array<string, InvalidException|InvalidFieldsException> $invalidFields
	 * @param string $message
	 * @param int $code
	 * @param Throwable|null $previous
	 */
	public function __construct(array $invalidFields, string $message = "", int $code = 0, Throwable $previous = null ) {
		$this->invalidFields = $invalidFields;
		parent::__construct( $message, $code, $previous );
	}

	/**
	 * @return array<string, InvalidException|InvalidFieldsException>
	 */
	public function getInvalidFields():array {
		return $this->invalidFields;
	}

	/**
	 * @return array<string, string>
	 */
	public function getAllMessages():array {
		$messages = [];
		foreach ( $this->invalidFields as $key => $value ) {
			if ($value instanceof InvalidFieldsException) {
				foreach ($value->getAllMessages() as $key2 => $message){
					$messages[$key . ':' . $key2] = $message;
				}
			} else {
				$messages[$key] = $value->getMessage();
			}
		}

		return $messages;
	}

	/**
	 * @return array<string, string|array<mixed>>
	 */
	public function getAllMessagesLayered():array {
		$messages = [];
		foreach ( $this->invalidFields as $key => $value ) {
			if ($value instanceof InvalidFieldsException) {
				$messages[$key] = $value->getAllMessagesLayered();
			} else {
				$messages[$key] = $value->getMessage();
			}
		}

		return $messages;
	}
}