<?php
/**
 * PastMatchesBackfill — replays eligible past matches when a play is activated.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

class PastMatchesBackfill {

	private Plugin $plugin;

	public function __construct( Plugin $plugin ) {
		$this->plugin = $plugin;
		add_action( 'cartcue_backfill_past_matches', [ $this, 'run' ], 10, 2 );
	}

	public function run( int $workflow_id, string $trigger_slug ): void {
		$workflow = $this->plugin->runner->get_workflow( $workflow_id );
		if ( ! $workflow || 'active' !== ( $workflow['status'] ?? '' ) ) {
			return;
		}

		$this->dispatch_for_resource( $workflow_id, $workflow, $trigger_slug );
	}

	private function dispatch_for_resource( int $workflow_id, array $workflow, string $trigger_slug ): void {
		$resource = $this->resolve_resource( $trigger_slug );
		if ( 'customer' === $resource ) {
			$this->dispatch_customers( $workflow_id, $workflow );
			return;
		}
		if ( 'order' === $resource ) {
			$this->dispatch_orders( $workflow_id, $workflow );
		}
	}

	private function dispatch_customers( int $workflow_id, array $workflow ): void {
		$page = 1;
		$per  = 200;

		while ( true ) {
			$query = new \WP_User_Query(
				[
					'role'    => 'customer',
					'number'  => $per,
					'paged'   => $page,
					'fields'  => 'ID',
					'orderby' => 'ID',
					'order'   => 'ASC',
				]
			);
			$user_ids = $query->get_results();
			if ( empty( $user_ids ) ) {
				break;
			}

			foreach ( $user_ids as $user_id ) {
				$user = get_user_by( 'id', (int) $user_id );
				if ( ! $user ) {
					continue;
				}

				$data = [
					'trigger'        => $workflow['trigger_slug'] ?? '',
					'customer_id'    => (int) $user_id,
					'customer_email' => (string) $user->user_email,
					'_backfill'      => true,
				];
				$this->plugin->runner->trigger( $workflow_id, $data );
			}

			if ( count( $user_ids ) < $per ) {
				break;
			}
			$page++;
		}
	}

	private function dispatch_orders( int $workflow_id, array $workflow ): void {
		$page = 1;
		$per  = 100;

		while ( true ) {
			$order_ids = wc_get_orders(
				[
					'limit'  => $per,
					'page'   => $page,
					'status' => [ 'completed', 'processing' ],
					'return' => 'ids',
				]
			);
			if ( empty( $order_ids ) ) {
				break;
			}

			foreach ( $order_ids as $order_id ) {
				$order = wc_get_order( (int) $order_id );
				if ( ! $order ) {
					continue;
				}

				$data = [
					'trigger'        => $workflow['trigger_slug'] ?? '',
					'order_id'       => $order->get_id(),
					'customer_id'    => $order->get_customer_id(),
					'customer_email' => $order->get_billing_email(),
					'_backfill'      => true,
				];
				$this->plugin->runner->trigger( $workflow_id, $data );
			}

			if ( count( $order_ids ) < $per ) {
				break;
			}
			$page++;
		}
	}

	private function resolve_resource( string $trigger_slug ): string {
		$customer_triggers = [
			'customer_created',
			'customer_win_back',
			'customer_never_purchased',
			'customer_birthday',
			'manual',
		];
		if ( in_array( $trigger_slug, $customer_triggers, true ) ) {
			return 'customer';
		}
		if ( 0 === strpos( $trigger_slug, 'cart_' ) || 0 === strpos( $trigger_slug, 'checkout_' ) ) {
			return 'cart';
		}

		return 'order';
	}
}
