<?php

namespace WPDRMS\ASP\Index;

use WPDRMS\ASP\Index\ORM\IndexSkipTable;
use WPDRMS\ASP\Index\ORM\IndexTable;
use WPDRMS\ASP\Index\ORM\IndexTableOptions;
use WPDRMS\PluginCore\Traits\SingletonTrait;

class IndexService {
	use SingletonTrait;

	public function createTables(): void {
		IndexTable::createTable();
		IndexSkipTable::createTable();
	}

	private function makeManager( array $args = array() ): IndexProcessor {
		$default_args = IndexTableOptions::instance()->toManagerArgs();

		return new IndexProcessor( array_merge( $default_args, $args ) );
	}

	public function index( array $args = array() ): array {
		return $this->makeManager( $args )->extendIndex( );
	}

	public function indexPost( int $post_id ): bool {
		return $this->makeManager()->indexDocument( $post_id );
	}

	public function delete( ?int $post_id = null ): void {
		if ( $post_id ) {
			$this->makeManager()->removeDocument( $post_id );
		} else {
			$this->makeManager()->emptyIndex();
			$this->makeManager()->beforeIndex();
		}
	}

	public function postsIndexed(): int {
		return $this->makeManager()->getPostsIndexed();
	}

	public function postsToIndexCount(): int {
		return $this->makeManager()->getPostIdsToIndexCount();
	}

	public function totalKeywords(): int {
		return $this->makeManager()->getTotalKeywords();
	}

	public function recordDailySnapshot(): void {
		$this->recordSnapshotToOption( 'asp_index_size_history',    $this->postsIndexed() );
		$this->recordSnapshotToOption( 'asp_index_keyword_history', $this->totalKeywords() );
	}

	private function recordSnapshotToOption( string $option, int $value ): void {
		$history = (array) get_site_option( $option, array() );
		$today   = date( 'Y-m-d' );
		$last    = ! empty( $history ) ? end( $history ) : null;
		if ( $last && $last['date'] === $today && (int) $last['count'] === $value ) {
			return;
		}
		if ( $last && $last['date'] === $today ) {
			$history[ count( $history ) - 1 ]['count'] = $value;
		} else {
			$history[] = array(
				'date'  => $today,
				'count' => $value,
			);
		}
		update_site_option( $option, array_slice( $history, -30 ) );
	}

	public static function scheduleSnapshotCron(): void {
		if ( ! wp_next_scheduled( 'asp_index_size_snapshot' ) ) {
			wp_schedule_event( time(), 'daily', 'asp_index_size_snapshot' );
		}
	}
}
