<?php

namespace wpsolr\core\classes\engines\postgresql;

use PgSql\Result;
use wpsolr\core\classes\engines\WPSOLR_AbstractResultsClient;

class WPSOLR_Results_PostgreSQL_Client extends WPSOLR_AbstractResultsClient {

	protected array $result;
	protected mixed $_response;

	public function __construct( Result $results ) {
		$this->raw_results = $results;

		$pg_row          = pg_fetch_assoc( $this->raw_results );
		$this->_response = json_decode( $pg_row['response'], true );
		pg_free_result( $this->raw_results );

		$this->results = $this->_get_results();
	}

	public function get_suggestions() {

		$suggests = $this->results['suggest'] ?? [];

		$suggests_array = [];
		if ( isset( $suggests[ WPSOLR_Search_PostgreSQL_Client::SUGGESTER_NAME ] ) ) {
			foreach ( $suggests[ WPSOLR_Search_PostgreSQL_Client::SUGGESTER_NAME ][0]['options'] as $option ) {
				array_push( $suggests_array, [ 'text' => $option['text'] ] );
			}
		}

		return $suggests_array;
	}

	protected function _get_results() {
		if ( isset( $this->results ) ) {
			return $this->results;
		}

		$results = [];
		foreach ( $this->_response['results'] as $result ) {
			foreach ( $result as $field_name => $field_value_pg ) {
				$field_value           = $this->_convert_from_pg( $field_value_pg );
				$result[ $field_name ] = ( is_null( $field_value ) || is_scalar( $field_value ) ) ?
					$field_value : ( empty( $field_value ) ? [] : $field_value[0] );
			}
			$results[] = (object) $result;
		}

		return $results;
	}

	function _convert_from_pg( mixed $value ) {
		if ( is_string( $value ) && str_starts_with( $value, '{' ) && str_ends_with( $value, '}' ) ) {
			// Convert Postgres array literal "{...}" to PHP array
			return explode( ',', trim( $value, '{}' ) );
		}

		return $value;
	}

	public function get_nb_results() {
		return $this->get_results() ? (int) $this->get_results()[0]->total_count : 0;
	}

	public function get_nb_rows() {
		return count( $this->results );
	}

	public function get_cursor_mark() {
		return '';
	}

	public function get_facet( $facet_name ) {

		$facets = [];
		foreach ( $this->_response['facets'][ $facet_name ] ?? [] as $facet ) {
			$facets[ $facet['value'] ?? sprintf( '%s-%s', $facet['from'], $facet['to'] ) ] = $facet['count'];
		}

		return $facets;
	}

	public function get_highlighting( $result ) {
		return [];
	}

	public function get_stats( $facet_name, array $options = [] ) {

		$aggregation = $this->_response['facets'][ $facet_name ] ?? [];


		return [ sprintf( '%s-%s', $aggregation['min'], $aggregation['max'] ) => $aggregation['count'] ];
	}

	public function get_top_hits( $field_name ) {
		$top_hits = [];
		foreach ( $this->get_results() as $result ) {
			$top_hits[ $result->$field_name ][] = $result;
		}

		return $top_hits;
	}
}
