<?php
/**
 * Bearer Authentication Strategy
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Strategies\Authentication
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Strategies\Authentication;

use WP_Error;
use MOWCPS\Common\Abstracts\Auth_Base_Strategy;
use MOWCPS\Common\Constants\Constants;

if ( ! defined( 'ABSPATH' ) ) {
	die;
}

/**
 * Class BearerAuth_Strategy
 *
 * Handles bearer token authentication
 */
class Bearer_Auth_Strategy extends Auth_Base_Strategy {
	/**
	 * Generate authorization headers
	 *
	 * @param int   $supplier_id Supplier ID.
	 * @param array $settings Auth settings.
	 * @return array|WP_Error Headers array or error
	 */
	public function generate_headers( $settings, $supplier_id ) {
		// Validate settings first.
		$validation = $this->validate_settings( $settings );
		if ( is_wp_error( $validation ) ) {
			return $validation;
		}

		$token       = $settings['token'];
		$token_type  = $settings['token_type'] ?? Constants::DEFAULT_TOKEN_TYPE;
		$header_name = $settings['authorization_header_name'] ?? Constants::DEFAULT_AUTH_HEADER_NAME;

		return array(
			$header_name => $token_type . ' ' . $token,
		);
	}

	/**
	 * Validate auth settings
	 *
	 * @param array $settings Auth settings.
	 * @return bool|WP_Error True if valid, WP_Error if invalid
	 */
	public function validate_settings( $settings ) {
		if ( empty( $settings['token'] ) ) {
			return new WP_Error(
				'invalid_bearer_auth_settings',
				'Invalid bearer auth settings: missing token',
				array( 'status' => 400 )
			);
		}

		return true;
	}
}
