<?php

namespace CelerSearch\Utilities;

defined( 'ABSPATH' ) || exit;

/**
 * Stores recent sync errors in a WP option for admin visibility.
 *
 * Acts as a ring buffer — keeps the most recent MAX_ERRORS entries.
 */
class SyncErrorLog {

	const OPTION_KEY = 'celersearch_recent_sync_errors';
	const MAX_ERRORS = 50;

	/**
	 * Record a sync error.
	 *
	 * @param string $index_slug
	 * @param mixed  $object_id
	 * @param string $error_message
	 * @param string $context 'sync' or 'delete'
	 *
	 * @return void
	 */
	public static function record( string $index_slug, $object_id, string $error_message, string $context = 'sync' ): void {
		$errors = get_option( self::OPTION_KEY, [] );

		$errors[] = [
			'timestamp'  => gmdate( 'Y-m-d H:i:s' ),
			'index_slug' => $index_slug,
			'object_id'  => $object_id,
			'error'      => $error_message,
			'context'    => $context,
		];

		if ( count( $errors ) > self::MAX_ERRORS ) {
			$errors = array_slice( $errors, - self::MAX_ERRORS );
		}

		update_option( self::OPTION_KEY, $errors, false );
	}

	/**
	 * Get recent errors (newest first).
	 *
	 * @param int $limit
	 *
	 * @return array
	 */
	public static function get_recent( int $limit = 20 ): array {
		$errors = get_option( self::OPTION_KEY, [] );

		return array_slice( array_reverse( $errors ), 0, $limit );
	}

	/**
	 * Get total error count.
	 *
	 * @return int
	 */
	public static function count(): int {
		$errors = get_option( self::OPTION_KEY, [] );

		return count( $errors );
	}

	/**
	 * Clear all stored errors.
	 *
	 * @return void
	 */
	public static function clear(): void {
		delete_option( self::OPTION_KEY );
	}
}
