<?php

// phpcs:disable Yoast.NamingConventions.NamespaceName.TooLong -- Needed in the folder structure.
namespace Yoast\WP\SEO\Bulk_Editor\Infrastructure\Posts;

use Yoast\WP\Lib\ORM;
use Yoast\WP\SEO\Bulk_Editor\Application\Posts\Posts_Collector_Interface;
use Yoast\WP\SEO\Bulk_Editor\Domain\Posts\Post;
use Yoast\WP\SEO\Bulk_Editor\Domain\Posts\Posts_List;
use Yoast\WP\SEO\Bulk_Editor\Domain\Posts\Posts_Page;
use Yoast\WP\SEO\Bulk_Editor\Domain\Posts\Posts_Query;
use Yoast\WP\SEO\Models\Indexable;
use Yoast\WP\SEO\Repositories\Indexable_Repository;

/**
 * Collects bulk editor posts by reading from the indexable table.
 *
 * This is the default used when indexables are active.
 */
class Indexable_Posts_Collector implements Posts_Collector_Interface {

	use Post_Title_Trait;
	use Searchable_Fields_Trait;

	/**
	 * Maps each "needs improvement" field key to its indexable column.
	 *
	 * @var array<string, string>
	 */
	private const FIELD_COLUMNS = [
		'seo_title'          => 'title',
		'meta_description'   => 'description',
		'social_title'       => 'open_graph_title',
		'social_description' => 'open_graph_description',
	];

	/**
	 * Maps the fields with a persisted per-field score to their indexable score column.
	 *
	 * The social fields have no assessors, so they match on emptiness only.
	 *
	 * @var array<string, string>
	 */
	private const FIELD_SCORE_COLUMNS = [
		'seo_title'        => 'seo_title_score',
		'meta_description' => 'meta_description_score',
	];

	/**
	 * The indexable repository.
	 *
	 * @var Indexable_Repository
	 */
	private $indexable_repository;

	/**
	 * The resolver for the per-post edit permission.
	 *
	 * @var Post_Editability_Resolver
	 */
	private $post_editability_resolver;

	/**
	 * The resolver for the post type's default SEO title / meta description template.
	 *
	 * @var Default_Template_Resolver
	 */
	private $default_template_resolver;

	/**
	 * The constructor.
	 *
	 * @param Indexable_Repository      $indexable_repository      The indexable repository.
	 * @param Post_Editability_Resolver $post_editability_resolver The resolver for the per-post edit permission.
	 * @param Default_Template_Resolver $default_template_resolver The resolver for the default SEO title / meta description template.
	 */
	public function __construct(
		Indexable_Repository $indexable_repository,
		Post_Editability_Resolver $post_editability_resolver,
		Default_Template_Resolver $default_template_resolver
	) {
		$this->indexable_repository      = $indexable_repository;
		$this->post_editability_resolver = $post_editability_resolver;
		$this->default_template_resolver = $default_template_resolver;
	}

	/**
	 * Collects a page of posts for the given query.
	 *
	 * A single page is fetched and counted through the database; the per-post edit permission is then
	 * resolved for that page so posts the user cannot edit are returned locked and without their SEO data.
	 *
	 * @param Posts_Query $query The query describing the page to collect.
	 *
	 * @return Posts_Page The collected posts together with the totals for pagination.
	 */
	public function get_posts( Posts_Query $query ): Posts_Page {
		$indexables = $this->build_query( $query )
			->order_by_desc( 'object_id' )
			->limit( $query->get_per_page() )
			->offset( $query->get_offset() )
			->find_many();

		// Deduplicate on the post, keeping the query order.
		$indexables_by_id = [];
		foreach ( $indexables as $indexable ) {
			$indexables_by_id[ (int) $indexable->object_id ] = $indexable;
		}

		$total = $this->resolve_total( $query, \count( $indexables ), \count( $indexables_by_id ) );

		$editability = $this->post_editability_resolver->resolve( \array_keys( $indexables_by_id ) );

		$posts_list = new Posts_List();
		foreach ( $indexables_by_id as $object_id => $indexable ) {
			$posts_list->add( $this->build_post( $indexable, ( $editability[ $object_id ] ?? false ), $query->are_scores_enabled() ) );
		}

		return new Posts_Page( $posts_list, $total, $query->get_page(), $query->get_per_page() );
	}

	/**
	 * Resolves the total number of matching posts.
	 *
	 * A partially-filled page means the result set ended within it, so the total is known without a
	 * second query: the offset plus the distinct posts on this page. Whether the page ended is judged
	 * on the number of rows fetched, before duplicates are removed, since that is what reveals the
	 * database had no more rows. A full or empty page does not reveal the total, so it falls back to a
	 * count query. Non-editable posts are shown locked rather than removed, so they still count.
	 *
	 * @param Posts_Query $query    The query that produced the page.
	 * @param int         $fetched  The number of rows the page returned, before duplicates are removed.
	 * @param int         $distinct The number of distinct posts on the page, after duplicates are removed.
	 *
	 * @return int The total number of matching posts.
	 */
	private function resolve_total( Posts_Query $query, int $fetched, int $distinct ): int {
		if ( $fetched > 0 && $fetched < $query->get_per_page() ) {
			return ( $query->get_offset() + $distinct );
		}

		return (int) $this->build_query( $query )->count();
	}

	/**
	 * Builds the filtered indexable query for the given query, without ordering or paging.
	 *
	 * Built fresh for each use so the same filters back both the total count and the page of rows.
	 *
	 * @param Posts_Query $query The query describing the filters to apply.
	 *
	 * @return ORM The filtered query.
	 */
	private function build_query( Posts_Query $query ): ORM {
		$builder = $this->indexable_repository->query()
			->where( 'object_type', 'post' )
			->where( 'object_sub_type', $query->get_content_type() )
			->where_in( 'post_status', $query->get_statuses() )
			// Password-protected posts (is_protected) are not shown in bulk editing.
			->where( 'is_protected', 0 );

		if ( $query->has_author_filter() ) {
			$builder->where( 'author_id', $query->get_author_id() );
		}

		if ( $query->has_include() ) {
			$builder->where_in( 'object_id', $query->get_include_ids() );
		}

		if ( $query->has_search() ) {
			$this->apply_search( $builder, $query->get_search() );
		}

		if ( $query->get_needs_improvement() !== [] ) {
			$this->apply_needs_improvement( $builder, $query->get_needs_improvement(), $query->are_scores_enabled(), $query->get_content_type() );
		}

		return $builder;
	}

	/**
	 * Adds the "needs improvement" clause to the query.
	 *
	 * A field needs improvement when its indexable column is NULL or an empty string, or — for fields
	 * with a persisted per-field score and while scoring is enabled — when that score falls in the bad/ok
	 * range. The empty-value check is skipped for fields whose post type has a configured fallback template,
	 * since template-defaulted posts are not genuinely empty. The selected fields are OR-ed inside a single
	 * group so they broaden the result without interfering with the other filters, and unknown field keys
	 * are ignored.
	 *
	 * @param ORM           $builder        The query to add the clause to.
	 * @param array<string> $fields         The fields that need improvement.
	 * @param bool          $scores_enabled Whether the per-field scores may back the filter.
	 * @param string        $post_type      The post type slug.
	 *
	 * @return void
	 */
	private function apply_needs_improvement( ORM $builder, array $fields, bool $scores_enabled, string $post_type ): void {
		$has_fallback = [
			'seo_title'          => $this->default_template_resolver->resolve_seo_title( 0, $post_type, '' ) !== '',
			'meta_description'   => $this->default_template_resolver->resolve_meta_description( 0, $post_type, '' ) !== '',
			'social_title'       => $this->default_template_resolver->resolve_social_title( 0, $post_type, '' ) !== '',
			'social_description' => $this->default_template_resolver->resolve_social_description( 0, $post_type, '' ) !== '',
		];

		$clauses = [];
		$values  = [];
		foreach ( $fields as $field ) {
			if ( ! isset( self::FIELD_COLUMNS[ $field ] ) ) {
				continue;
			}

			$column        = self::FIELD_COLUMNS[ $field ];
			$field_clauses = [];

			if ( ! ( $has_fallback[ $field ] ?? false ) ) {
				$field_clauses[] = $column . ' IS NULL OR ' . $column . ' = %s';
				$values[]        = '';
			}

			if ( $scores_enabled && isset( self::FIELD_SCORE_COLUMNS[ $field ] ) ) {
				$field_clauses[] = self::FIELD_SCORE_COLUMNS[ $field ] . ' BETWEEN %d AND %d';
				$values[]        = self::NEEDS_IMPROVEMENT_MIN_SCORE;
				$values[]        = self::NEEDS_IMPROVEMENT_MAX_SCORE;
			}

			// Always add a clause per field — use a false condition when no real predicate applies so the
			// field still participates in the outer OR group without incorrectly matching every row.
			$clauses[] = '( ' . ( ( $field_clauses !== [] ) ? \implode( ' OR ', $field_clauses ) : '1 = 0' ) . ' )';
		}

		if ( $clauses === [] ) {
			return;
		}

		// The column names come from the internal maps, never from input; only the empty string and score bounds are bound.
		$builder->where_raw(
			'( ' . \implode( ' OR ', $clauses ) . ' )',
			$values,
		);
	}

	/**
	 * Adds the catch-all search clause to the query.
	 *
	 * The post title lives in the posts table, so it is matched through a subquery while the remaining
	 * fields are matched directly on the indexable. All clauses are OR-ed inside a single group so they
	 * do not interfere with the other filters.
	 *
	 * @param ORM    $builder The query to add the search clause to.
	 * @param string $search  The search term.
	 *
	 * @return void
	 */
	private function apply_search( ORM $builder, string $search ): void {
		global $wpdb;

		$like = '%' . $wpdb->esc_like( $search ) . '%';

		// The post title lives in the posts table, so match it through a subquery; the rest are indexable columns.
		$clauses = [ 'object_id IN ( SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title LIKE %s )' ];
		foreach ( \array_keys( $this->searchable_fields() ) as $column ) {
			$clauses[] = $column . ' LIKE %s';
		}

		// The ORM binds each %s through $wpdb->prepare; one bound value per clause.
		$builder->where_raw(
			'( ' . \implode( ' OR ', $clauses ) . ' )',
			\array_fill( 0, \count( $clauses ), $like ),
		);
	}

	/**
	 * Builds a post from an indexable.
	 *
	 * The SEO data and edit link of a post the current user cannot edit are withheld, so the post is
	 * shown in the list but stays locked and does not expose its metadata.
	 *
	 * @param Indexable $indexable      The indexable.
	 * @param bool      $editable       Whether the current user may edit the post.
	 * @param bool      $scores_enabled Whether the per-field scores may back the needs-improvement verdict.
	 *
	 * @return Post The post.
	 */
	private function build_post( Indexable $indexable, bool $editable, bool $scores_enabled ): Post {
		$object_id = (int) $indexable->object_id;
		$title     = $this->get_normalized_title( $object_id );

		if ( ! $editable ) {
			return new Post( $object_id, $title, (string) $indexable->post_status, '', '', '', '', '', '', false );
		}

		$post_type = (string) $indexable->object_sub_type;

		$raw_seo_title          = (string) $indexable->title;
		$raw_meta_description   = (string) $indexable->description;
		$raw_social_title       = (string) $indexable->open_graph_title;
		$raw_social_description = (string) $indexable->open_graph_description;

		// Resolver results are used for needs-improvement scoring and as display fallbacks when the stored value is empty.
		$resolved_values = [
			'seo_title'          => $this->default_template_resolver->resolve_seo_title( $object_id, $post_type, $raw_seo_title ),
			'meta_description'   => $this->default_template_resolver->resolve_meta_description( $object_id, $post_type, $raw_meta_description ),
			'social_title'       => $this->default_template_resolver->resolve_social_title( $object_id, $post_type, $raw_social_title ),
			'social_description' => $this->default_template_resolver->resolve_social_description( $object_id, $post_type, $raw_social_description ),
		];

		return new Post(
			$object_id,
			$title,
			(string) $indexable->post_status,
			(string) \get_edit_post_link( $object_id, 'raw' ),
			(string) $indexable->primary_focus_keyword,
			$raw_seo_title,
			$raw_meta_description,
			$raw_social_title,
			$raw_social_description,
			true,
			$this->build_needs_improvement( $indexable, $scores_enabled, $resolved_values ),
			( $raw_seo_title === '' ) ? $resolved_values['seo_title'] : '',
			( $raw_meta_description === '' ) ? $resolved_values['meta_description'] : '',
			( $raw_social_title === '' ) ? $resolved_values['social_title'] : '',
			( $raw_social_description === '' ) ? $resolved_values['social_description'] : '',
		);
	}

	/**
	 * Builds the per-field needs-improvement verdict for a post, keyed by field param.
	 *
	 * A field needs improvement when its value is empty, or when its score falls in the bad/ok range.
	 * All four display values are passed in already-resolved so that a post whose stored value is empty
	 * but whose post type has a configured default template is not incorrectly flagged.
	 *
	 * @param Indexable             $indexable       The indexable.
	 * @param bool                  $scores_enabled  Whether the per-field scores may back the verdict.
	 * @param array<string, string> $resolved_values The resolved display values, keyed by field param.
	 *
	 * @return array<string, bool> Whether each field needs improvement, keyed by field param.
	 */
	private function build_needs_improvement( Indexable $indexable, bool $scores_enabled, array $resolved_values ): array {
		$needs_improvement = [];
		foreach ( self::FIELD_COLUMNS as $field => $column ) {
			$value    = $resolved_values[ $field ];
			$is_empty = ( $value === '' );

			$is_bad_score = false;
			if ( $scores_enabled && isset( self::FIELD_SCORE_COLUMNS[ $field ] ) ) {
				$score        = (int) $indexable->{self::FIELD_SCORE_COLUMNS[ $field ]};
				$is_bad_score = ( $score >= self::NEEDS_IMPROVEMENT_MIN_SCORE && $score <= self::NEEDS_IMPROVEMENT_MAX_SCORE );
			}

			$needs_improvement[ $field ] = ( $is_empty || $is_bad_score );
		}

		return $needs_improvement;
	}
}
