<?php
declare( strict_types=1 );

namespace FiboFilters\API;

use FiboFilters\Config\Troubleshooting as TroubleshootingConfig;
use WP_Error;
use WP_Http;
use WP_REST_Request;
use WP_REST_Response;

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

/**
 * Class Troubleshooting
 */
class Troubleshooting {

	/** @var TroubleshootingConfig */
	private $troubleshooting;

	public function __construct( TroubleshootingConfig $troubleshooting ) {
		$this->troubleshooting = $troubleshooting;
	}

	/**
	 * @param WP_REST_Request $request Request.
	 *
	 * @return WP_Error|WP_REST_Response
	 */
	public function test( WP_REST_Request $request ) {
		$test = $request->get_param( 'test' );
		$type = $request->get_param( 'type' );

		try {
			$result = $this->troubleshooting->get_test_result( $test, $type );
		} catch ( \Throwable $exception ) {
			return new WP_Error(
				'fibofilters_troubleshooting_test_error',
				$exception->getMessage()
			);
		}

		return new WP_REST_Response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 *
	 * @return WP_Error|WP_REST_Response
	 */
	public function save_test_result( WP_REST_Request $request ) {
		$test_result = $request->get_param( 'test_result' );

		$this->troubleshooting->save_test_result( $test_result );

		return new WP_REST_Response( [] );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 *
	 * @return WP_Error|WP_REST_Response
	 */
	public function do_action( WP_REST_Request $request ) {
		$action = $request->get_param( 'action' );
		$args   = $request->get_param( 'args' );
		if ( empty( $args ) ) {
			$args = [];
		}

		try {
			$result = $this->troubleshooting->do_action( $action, $args );
		} catch ( \Throwable $exception ) {
			return new WP_Error(
				'fibofilters_troubleshooting_action_error',
				$exception->getMessage(),
				[
					'status' => WP_Http::BAD_REQUEST,
				]
			);
		}

		return new WP_REST_Response( $result );
	}
}
