<?php
/**
 * Integration Route Descriptor
 *
 * Value object that describes an integration's REST API configuration.
 *
 * @package Sequensy
 * @since 2.0.0
 */

declare(strict_types=1);

namespace Sequensy\Rest;

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

/**
 * Class IntegrationRouteDescriptor
 *
 * Immutable configuration for integration REST routes.
 */
class IntegrationRouteDescriptor {

	/**
	 * Integration slug (e.g., 'mailchimp', 'airtable').
	 *
	 * @var string
	 */
	public readonly string $slug;

	/**
	 * Human-readable display name.
	 *
	 * @var string
	 */
	public readonly string $display_name;

	/**
	 * Credential field definitions.
	 *
	 * @var array
	 */
	public readonly array $credential_fields;

	/**
	 * Sub-route definitions.
	 *
	 * @var array
	 */
	public readonly array $sub_routes;

	/**
	 * Constructor.
	 *
	 * @param string $slug              Integration slug.
	 * @param string $display_name      Human-readable name.
	 * @param array  $credential_fields Credential field definitions.
	 * @param array  $sub_routes        Sub-route definitions.
	 */
	public function __construct(
		string $slug,
		string $display_name,
		array $credential_fields,
		array $sub_routes = array()
	) {
		$this->slug              = $slug;
		$this->display_name      = $display_name;
		$this->credential_fields = $credential_fields;
		$this->sub_routes        = $sub_routes;
	}

	/**
	 * Get the base route path.
	 *
	 * @return string Route path like 'integrations/mailchimp'.
	 */
	public function get_base_route(): string {
		return 'integrations/' . $this->slug;
	}

	/**
	 * Get REST API argument definitions for connect endpoint.
	 *
	 * @return array WordPress REST API args array.
	 */
	public function get_connect_args(): array {
		$args = array();

		foreach ( $this->credential_fields as $field => $config ) {
			$args[ $field ] = array(
				'required'          => $config['required'] ?? true,
				'type'              => $config['type'] ?? 'string',
				'sanitize_callback' => $config['sanitize_callback'] ?? 'sanitize_text_field',
				'validate_callback' => $config['validate_callback'] ?? 'rest_validate_request_arg',
			);
		}

		return $args;
	}

	/**
	 * Extract credentials from request.
	 *
	 * @param \WP_REST_Request $request REST request.
	 * @return array Extracted credentials.
	 */
	public function extract_credentials( \WP_REST_Request $request ): array {
		$credentials = array();

		foreach ( $this->credential_fields as $field => $config ) {
			$credentials[ $field ] = $request->get_param( $field );
		}

		return $credentials;
	}
}
