<?php
// DESCRIPTION: Monitors sync results and triggers admin notifications when consecutive
// failures reach a configurable threshold for any integration.

namespace SheetWise\Sync;

class FailureNotifier {

	/**
	 * The sync logger instance
	 *
	 * @since 2.0.0
	 *
	 * @var SyncLogger
	 */
	private $logger;

	/**
	 * Initialize the failure notifier
	 *
	 * @since 2.0.0
	 *
	 * @param SyncLogger $logger
	 */
	public function __construct( SyncLogger $logger ) {
		$this->logger = $logger;

		add_action( 'swise_sync_completed', [ $this, 'check_consecutive_failures' ], 20, 2 );
		add_action( 'admin_notices', [ $this, 'display_failure_notices' ] );
	}

	/**
	 * Check for consecutive failures after each sync and set a transient if threshold is reached
	 *
	 * @since 2.0.0
	 *
	 * @param array $sync_result Result from RetryHandler
	 * @param array $context     Sync context with integration_id, hook, etc.
	 *
	 * @return void
	 */
	public function check_consecutive_failures( $sync_result, $context ) {
		// Only check on failure
		if ( $sync_result['status'] === 'success' ) {
			// Clear any existing failure notice for this integration
			$integration_id = $context['integration_id'] ?? 0;
			if ( $integration_id ) {
				delete_transient( 'swise_sync_failure_notice_' . $integration_id );
			}

			return;
		}

		$integration_id = $context['integration_id'] ?? 0;

		if ( ! $integration_id ) {
			return;
		}

		$consecutive_failures = $this->logger->get_consecutive_failures( $integration_id );

		/**
		 * Filter the number of consecutive failures before triggering a notification
		 *
		 * @since 2.0.0
		 *
		 * @param int $threshold      Number of consecutive failures (default: 3)
		 * @param int $integration_id The integration post ID
		 */
		$threshold = apply_filters( 'swise_failure_notification_threshold', 3, $integration_id );

		if ( $consecutive_failures >= $threshold ) {
			$integration = get_post( $integration_id );
			$title       = $integration ? $integration->post_title : sprintf(
				/* translators: %d: integration ID */
				__( 'Integration #%d', 'sheet-wise' ),
				$integration_id
			);

			set_transient(
				'swise_sync_failure_notice_' . $integration_id,
				[
					'integration_id' => $integration_id,
					'title'          => $title,
					'failure_count'  => $consecutive_failures,
					'last_error'     => $sync_result['error']['message'] ?? '',
				],
				DAY_IN_SECONDS
			);
		}
	}

	/**
	 * Display admin notices for sync failures
	 *
	 * @since 2.0.0
	 *
	 * @return void
	 */
	public function display_failure_notices() {
		if ( ! current_user_can( swise_get_admin_capability() ) ) {
			return;
		}

		// Only show on Sheet Wise admin pages
		$screen = get_current_screen();
		if ( ! $screen || strpos( $screen->id, 'sheet-wise' ) === false ) {
			return;
		}

		$integrations = get_posts( [
			'post_type'      => swise_get_post_type(),
			'posts_per_page' => -1,
			'post_status'    => 'publish',
			'fields'         => 'ids',
		] );

		foreach ( $integrations as $integration_id ) {
			$notice_data = get_transient( 'swise_sync_failure_notice_' . $integration_id );

			if ( ! $notice_data ) {
				continue;
			}

			printf(
				'<div class="notice notice-error"><p>%s</p></div>',
				sprintf(
					/* translators: 1: integration name, 2: failure count, 3: last error message */
					esc_html__( 'Sheet Wise: "%1$s" has failed %2$d times in a row. Last error: %3$s', 'sheet-wise' ),
					esc_html( $notice_data['title'] ),
					(int) $notice_data['failure_count'],
					esc_html( $notice_data['last_error'] )
				)
			);
		}
	}
}
