<?php

namespace SugarCalendarBookings\Integrations\Outlook;

use SugarCalendarBookings\Integrations\OAuthRelay\AbstractOAuthCallbackHandler;
use SugarCalendarBookings\Integrations\OAuthRelay\OAuthConnectionModel;
use SugarCalendarBookings\Integrations\OAuthRelay\OAuthRelayClient;
use SugarCalendarBookings\Integrations\Webhooks\IncomingWebhookHandler;
use SugarCalendarBookings\Integrations\Webhooks\WebhookUrlMonitor;

/**
 * Outlook OAuth callback handler.
 *
 * @since 1.5.0
 */
class OutlookOAuthCallbackHandler extends AbstractOAuthCallbackHandler {

	/**
	 * Outlook subscription manager.
	 *
	 * @since 1.5.0
	 *
	 * @var OutlookSubscriptionManager
	 */
	private OutlookSubscriptionManager $subscription_manager;

	/**
	 * Constructor.
	 *
	 * @since 1.5.0
	 *
	 * @param OAuthRelayClient           $oauth_client         OAuth relay client (used for token exchange).
	 * @param OutlookSubscriptionManager $subscription_manager Microsoft Graph subscription manager.
	 */
	public function __construct( OAuthRelayClient $oauth_client, OutlookSubscriptionManager $subscription_manager ) {

		parent::__construct( $oauth_client );

		$this->subscription_manager = $subscription_manager;
	}

	/**
	 * Get the provider identifier.
	 *
	 * @since 1.5.0
	 *
	 * @return string
	 */
	protected function get_provider(): string {

		return 'outlook';
	}

	/**
	 * Register Microsoft Graph subscriptions via the dedicated relay endpoint.
	 *
	 * Outlook does not go through the relay's `/webhooks/register` endpoint
	 * (which is Zoom-specific). Instead it hits
	 * `/integrations/v1/{license}/subscriptions`, the dedicated Graph
	 * subscription endpoint, via {@see OutlookSubscriptionManager}.
	 *
	 * Subscriptions are per conflict calendar, so we reconcile against the
	 * connection's current selection. At connect time that selection is often
	 * empty (the user picks calendars afterwards), in which case this is a
	 * no-op and subscriptions are created when the selection is saved.
	 *
	 * @since 1.5.0
	 *
	 * @param OAuthConnectionModel $connection The stored connection.
	 */
	protected function maybe_register_webhook( OAuthConnectionModel $connection ): void {

		$webhook_url = IncomingWebhookHandler::get_webhook_url( $this->get_provider() );

		$this->subscription_manager->sync( $connection, $webhook_url );

		// Track the REST base URL so WebhookUrlMonitor can detect later changes
		// and re-register subscriptions. Mirrors the relay flow used by Zoom.
		update_option( WebhookUrlMonitor::OPTION_REST_BASE_URL, rest_url(), true );
	}
}
