<?php

namespace Limb_Chatbot\Includes\Widgets\Presenters;

use Limb_Chatbot\Includes\Services\Helper;
use WP_REST_Controller;
use WP_REST_Posts_Controller;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Converts posts into core REST payloads (wp/v2 or CPT schema), same approach as
 * {@see \Limb_Chatbot\Includes\Integrations\WooCommerce\Services\WC_Product_REST_Presenter}.
 *
 * @since 2.0.0
 */
final class Featured_Post_REST_Presenter {

	/**
	 * @param \WP_Post[] $posts
	 *
	 * @return array<int, array<string, mixed>>
	 */
	public function present( array $posts ): array {
		$out = [];
		foreach ( $posts as $post ) {
			if ( ! $post instanceof \WP_Post ) {
				continue;
			}
			$item = $this->prepare_post_for_response( $post );
			if ( is_array( $item ) ) {
				$out[] = $item;
			}
		}

		return $out;
	}

	/**
	 * @return array<string, mixed>|null
	 */
	public function prepare_post_for_response( \WP_Post $post ): ?array {
		try {
			$controller = $this->resolve_rest_controller( $post->post_type );
			if ( ! $controller instanceof WP_REST_Controller ) {
				return null;
			}

			$request = new WP_REST_Request();
			$request->set_param( 'context', 'edit' );

			$response = $controller->prepare_item_for_response( $post, $request );
			if ( ! $response instanceof WP_REST_Response ) {
				return null;
			}

			$data = $response->get_data();

			return is_array( $data ) ? $data : null;
		} catch ( \Throwable $e ) {
			Helper::log( $e, __METHOD__ . ' - post ' . $post->ID );

			return null;
		}
	}

	private function resolve_rest_controller( string $post_type ): ?WP_REST_Controller {
		$object = get_post_type_object( $post_type );
		if ( ! $object instanceof \WP_Post_Type ) {
			return null;
		}

		if ( $object->show_in_rest ) {
			$controller = $object->get_rest_controller();
			if ( $controller instanceof WP_REST_Controller ) {
				return $controller;
			}
		}

		return new WP_REST_Posts_Controller( $post_type );
	}
}
