<?php

declare(strict_types=1);

/**
 * This code was auto-generated by {this script}[https://github.com/cucumber/messages/blob/main/jsonschema/scripts/codegen.rb]
 */

namespace Cucumber\Messages;

use JsonSerializable;
use Cucumber\Messages\DecodingException\SchemaViolationException;

/**
 * Represents the Exception message in Cucumber's message protocol
 * @see https://github.com/cucumber/messages
 *
 * A simplified representation of an exception */
final class Exception implements JsonSerializable
{
    use JsonEncodingTrait;

    /**
     * Construct the Exception with all properties
     *
     */
    public function __construct(

        /**
         * The type of the exception that caused this result. E.g. "Error" or "org.opentest4j.AssertionFailedError"
         */
        public readonly string $type = '',

        /**
         * The message of exception that caused this result. E.g. expected: "a" but was: "b"
         */
        public readonly ?string $message = null,

        /**
         * The stringified stack trace of the exception that caused this result
         */
        public readonly ?string $stackTrace = null,
    ) {
    }

    /**
     * @throws SchemaViolationException
     *
     * @internal
     */
    public static function fromArray(array $arr): self
    {
        self::ensureType($arr);
        self::ensureMessage($arr);
        self::ensureStackTrace($arr);

        return new self(
            (string) $arr['type'],
            isset($arr['message']) ? (string) $arr['message'] : null,
            isset($arr['stackTrace']) ? (string) $arr['stackTrace'] : null,
        );
    }

    /**
     * @psalm-assert array{type: string|int|bool} $arr
     */
    private static function ensureType(array $arr): void
    {
        if (!array_key_exists('type', $arr)) {
            throw new SchemaViolationException('Property \'type\' is required but was not found');
        }
        if (array_key_exists('type', $arr) && is_array($arr['type'])) {
            throw new SchemaViolationException('Property \'type\' was array');
        }
    }

    /**
     * @psalm-assert array{message?: string|int|bool} $arr
     */
    private static function ensureMessage(array $arr): void
    {
        if (array_key_exists('message', $arr) && is_array($arr['message'])) {
            throw new SchemaViolationException('Property \'message\' was array');
        }
    }

    /**
     * @psalm-assert array{stackTrace?: string|int|bool} $arr
     */
    private static function ensureStackTrace(array $arr): void
    {
        if (array_key_exists('stackTrace', $arr) && is_array($arr['stackTrace'])) {
            throw new SchemaViolationException('Property \'stackTrace\' was array');
        }
    }
}
