<?php

/**
 * VAPPV_TTW_Exceptions_Environment
 * Common TTW class for handling errors
 */
final class VAPPV_TTW_Exceptions_Environment {

	/**
	 * Extract error from OpenAI API response
	 * @param  int|null $status_code
	 * @param string|null $openai_api_response_raw
	 * @return VAPPV_TTW_OpenAI_API_Error
	 */
	public static function extract_error_from_openai_response( ?int $status_code, ?string $openai_api_response_raw ) : VAPPV_TTW_OpenAI_API_Error {

		try {

			// Get assoc data
			$openai_api_response_assoc = json_decode( $openai_api_response_raw, true );

			//Check for "Error" field
			if (
				isset( $openai_api_response_assoc['error'] )
			) {

				$error_object = new VAPPV_TTW_OpenAI_API_Error();
				$error_object->code = $status_code;

				if ( isset( $openai_api_response_assoc['error']['message'] ) ) {
					$error_object->message = esc_html( $openai_api_response_assoc['error']['message'] );
				}
				if ( isset( $openai_api_response_assoc['error']['type'] ) ) {
					$error_object->type = esc_html( $openai_api_response_assoc['error']['type'] );
				}
				if ( isset( $openai_api_response_assoc['error']['param'] ) ) {
					$error_object->param = esc_html( $openai_api_response_assoc['error']['param'] );
				}

				return $error_object;

			}

			$unknown_error          = new VAPPV_TTW_OpenAI_API_Error();
			$unknown_error->code	= $status_code;
			$unknown_error->message = esc_html( $openai_api_response_raw );
			return $unknown_error;

		} catch ( Throwable $t ) {

			// Executed only in PHP 7+
			$atypical_error          = new VAPPV_TTW_OpenAI_API_Error();
			$atypical_error->code	 = $status_code;
			$atypical_error->message = esc_html( $openai_api_response_raw );
			return $atypical_error;

		}

	}

}

/**
 * TTW common error
 */
final class VAPPV_TTW_Common_Error {

	/**
	 * Error details
	 */
	public $message;

	/**
	 * Exception object
	 */
	public $exception_data;
}

/**
 * VAPPV_TTW_OpenAI_API_Error
 * ChatGPT API error details
 */
final class VAPPV_TTW_OpenAI_API_Error {
	/**
	 * message
	 * Thrown error plain text
	 * @var string
	 */
	public $message;

	/**
	 * type
	 * Thrown error type ("insufficient_quota" is quota is exceeded / not enough balance)
	 * @var string
	 */
	public $type;

	/**
	 * param
	 * Additional params
	 * @var mixed
	 */
	public $param;

	/**
	 * code
	 * Thrown error code (usually the same with $this->type param)
	 * @var mixed
	 */
	public $code;
}

/*
	© 2024 Copyright Vitalii A. Popov. All rights reserved.
*/

?>