<?php
/**
 * Detects multiple active email plays on the same trigger.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class PlayOverlap {

	/**
	 * @param array<int, array<string, mixed>> $plays Raw or decoded workflow rows.
	 * @return array<int, array{ trigger_slug: string, plays: array<int, array<string, mixed>> }>
	 */
	public static function find_groups( array $plays ): array {
		$by_trigger = [];

		foreach ( $plays as $play ) {
			if ( 'active' !== ( $play['status'] ?? '' ) ) {
				continue;
			}
			if ( ! WorkflowRunner::workflow_sends_email( $play ) ) {
				continue;
			}
			$slug = (string) ( $play['trigger_slug'] ?? '' );
			if ( '' === $slug ) {
				continue;
			}
			$by_trigger[ $slug ]   = $by_trigger[ $slug ] ?? [];
			$by_trigger[ $slug ][] = $play;
		}

		$groups = [];
		foreach ( $by_trigger as $slug => $group_plays ) {
			if ( count( $group_plays ) < 2 ) {
				continue;
			}
			$groups[] = [
				'trigger_slug' => $slug,
				'plays'        => $group_plays,
			];
		}

		return $groups;
	}

	/**
	 * @param array<int, array{ trigger_slug: string, plays: array<int, array<string, mixed>> }> $groups
	 */
	public static function play_is_in_overlap( int $play_id, array $groups ): bool {
		foreach ( $groups as $group ) {
			foreach ( $group['plays'] as $play ) {
				if ( (int) ( $play['id'] ?? 0 ) === $play_id ) {
					return true;
				}
			}
		}
		return false;
	}
}
