<?php

namespace Waypoint\Agent\Rest\Handler;

use Waypoint\Agent\Helpers\Blocks;

class Site_Inventory {

	public function handle( \WP_REST_Request $request ): \WP_REST_Response {
		$post_types = [ 'page', 'post' ];
		if ( post_type_exists( 'service' ) ) {
			$post_types[] = 'service';
		}

		$posts = get_posts( [
			'post_type'      => $post_types,
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'orderby'        => 'menu_order title',
			'order'          => 'ASC',
		] );

		$pages = [];
		foreach ( $posts as $post ) {
			$blocks      = parse_blocks( $post->post_content );
			$block_names = Blocks::collect_names( $blocks );
			$h2s         = Blocks::extract_headings( $post->post_content, 2 );

			$h1_candidates = Blocks::extract_headings( $post->post_content, 1 );
			$h1            = ! empty( $h1_candidates ) ? $h1_candidates[0] : get_the_title( $post->ID );

			$meta_description = (string) get_post_meta( $post->ID, 'rank_math_description', true );
			if ( '' === $meta_description ) {
				$meta_description = (string) get_post_meta( $post->ID, '_yoast_wpseo_metadesc', true );
			}

			$word_count = str_word_count( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ) );

			$pages[] = [
				'wp_post_id'       => $post->ID,
				'post_id'          => $post->ID,
				'url'              => get_permalink( $post->ID ),
				'slug'             => $post->post_name,
				'title'            => get_the_title( $post->ID ),
				'h1'               => $h1,
				'h2s'              => $h2s,
				'block_names'      => $block_names,
				'meta_description' => '' !== $meta_description ? $meta_description : null,
				'word_count'       => $word_count,
				'post_type'        => $post->post_type,
				'post_status'      => $post->post_status,
			];
		}

		return rest_ensure_response( [
			'pages'        => $pages,
			'total'        => count( $pages ),
			'generated_at' => gmdate( 'c' ),
		] );
	}
}
