<?php
/**
 * Campaign Monitor REST Routes
 *
 * @package Sequensy\Integrations\CampaignMonitor
 * @since 1.0.0
 */

declare(strict_types=1);

namespace Sequensy\Integrations\CampaignMonitor\Rest;

use Sequensy\Integrations\CampaignMonitor\CampaignMonitorApi;
use Sequensy\Rest\AbstractIntegrationRoutes;
use Sequensy\Rest\IntegrationRouteDescriptor;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Class CampaignMonitorRoutes
 *
 * Registers Campaign Monitor integration REST routes.
 */
class CampaignMonitorRoutes extends AbstractIntegrationRoutes {

	/**
	 * Configure the integration route descriptor.
	 *
	 * @return IntegrationRouteDescriptor
	 */
	protected function configure(): IntegrationRouteDescriptor {
		return new IntegrationRouteDescriptor(
			slug: 'campaignmonitor',
			display_name: __( 'Campaign Monitor', 'sequensy' ),
			credential_fields: array(
				'api_key'   => array(
					'required' => true,
					'type'     => 'string',
				),
				'client_id' => array(
					'required' => true,
					'type'     => 'string',
				),
			),
		);
	}

	/**
	 * Create a Campaign Monitor API instance with the given credentials.
	 *
	 * @param array $credentials Credential values with 'api_key'.
	 * @return CampaignMonitorApi API client instance.
	 */
	protected function create_api( array $credentials ): object {
		return new CampaignMonitorApi( $credentials['api_key'], $credentials['client_id'] );
	}

	/**
	 * Register integration-specific sub-routes.
	 *
	 * @return void
	 */
	protected function register_sub_routes(): void {
		$this->register_connection_get_route( 'lists', array( $this, 'get_lists' ) );
	}

	/**
	 * Get subscriber lists for a connection.
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 * @return WP_REST_Response|WP_Error Response object or error.
	 */
	public function get_lists( WP_REST_Request $request ): WP_REST_Response|WP_Error {
		$connection_id = $request->get_param( 'connection_id' );

		return $this->api_call_with_connection(
			$connection_id,
			fn( CampaignMonitorApi $api ) => $api->get_lists()
		);
	}
}
