<?php

namespace SugarCalendarBookings\Integrations;

use SugarCalendarBookings\Plugin;

/**
 * Meeting provider capability resolver.
 *
 * Answers the question "which meeting providers can this WP user deliver?"
 * in a batch-friendly way: given a list of user IDs, returns a map keyed
 * by user ID with a per-provider boolean.
 *
 * @since 1.4.0
 */
class MeetingProviderCapabilityResolver {

	/**
	 * Build a capability map for the given user IDs.
	 *
	 * Result shape: `[ user_id => [ provider_slug => bool, ... ], ... ]`.
	 * Every user ID in the input is present in the output with an entry
	 * for each registered meeting provider.
	 *
	 * @since 1.4.0
	 *
	 * @param int[] $user_ids Candidate WP user IDs.
	 *
	 * @return array<int, array<string, bool>>
	 */
	public function for_user_ids( array $user_ids ): array {

		$providers = Plugin::get( IntegrationCapabilityRegistry::class )->get( MeetingProviderInterface::class );
		$user_ids  = array_values( array_unique( array_map( 'intval', $user_ids ) ) );

		$capabilities = array_fill_keys( $user_ids, [] );

		foreach ( $providers as $provider ) {
			$slug    = $provider->get_provider_slug();
			$allowed = array_flip( $provider->get_deliverable_user_ids( $user_ids ) );

			foreach ( $user_ids as $user_id ) {
				$capabilities[ $user_id ][ $slug ] = isset( $allowed[ $user_id ] );
			}
		}

		return $capabilities;
	}

	/**
	 * Annotate a list of rows with their meeting delivery capability map.
	 *
	 * Each row is expected to carry a `user_id` field. A `can_deliver` key is
	 * added to every row, mapping provider slug to bool. Rows without a
	 * `user_id` receive an empty map.
	 *
	 * @since 1.4.0
	 *
	 * @param array $rows Rows that include a `user_id` field.
	 *
	 * @return array Same rows with a `can_deliver` key added.
	 */
	public function annotate_with_capabilities( array $rows ): array {

		$user_ids     = array_map(
			static fn( $row ) => (int) ( $row['user_id'] ?? 0 ),
			$rows
		);
		$capabilities = $this->for_user_ids( $user_ids );

		return array_map(
			static function ( $row ) use ( $capabilities ) {

				$user_id            = (int) ( $row['user_id'] ?? 0 );
				$row['can_deliver'] = $capabilities[ $user_id ] ?? [];

				return $row;
			},
			$rows
		);
	}
}
