<?php
/**
 * Authorization Handler for Sync
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Handlers\Sync
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Handlers\Sync;

use WP_Error;
use MOWCPS\Common\Constants\Constants;
use MOWCPS\Common\Models\Authorization_Model;
use MOWCPS\Common\Models\Supplier_Model;
use MOWCPS\Common\Services\Authorization\Authorization_Service;

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

/**
 * Class Authorization_Handler
 *
 * Handles authorization for sync processes
 * Manages data access and coordinates with authorization service
 */
class Authorization_Handler {
	/**
	 * Constructor
	 */
	public function __construct() {
	}

	/**
	 * Get authorization headers for a supplier
	 *
	 * @param int $supplier_id Supplier ID.
	 * @return array|WP_Error Headers array or error
	 */
	public function get_authorization_headers( $supplier_id ) {
		// Get authorization configuration from model.
		$auth_model  = new Authorization_Model();
		$auth_config = $auth_model->get_by_supplier_id( $supplier_id );

		if ( ! $auth_config ) {
			return new WP_Error(
				'auth_config_not_found',
				'Authorization configuration not found for supplier',
				array( 'status' => Constants::HTTP_NOT_FOUND )
			);
		}

		// Generate headers using the authorization service.
		$auth_service = new Authorization_Service();
		return $auth_service->generate_headers( $auth_config, $supplier_id );
	}

	/**
	 * Get authorization headers for a supplier by UUID
	 *
	 * @param string $supplier_uuid Supplier UUID.
	 * @return array|WP_Error Headers array or error
	 */
	public function get_authorization_headers_by_uuid( $supplier_uuid ) {
		// First, get the supplier to validate it exists and get the ID.
		$supplier_model = new Supplier_Model();
		$supplier       = $supplier_model->get_by_uuid( $supplier_uuid );
		if ( ! $supplier ) {
			return new WP_Error(
				Constants::ERROR_SUPPLIER_NOT_FOUND,
				Constants::MSG_SUPPLIER_NOT_FOUND,
				array( 'status' => Constants::HTTP_NOT_FOUND )
			);
		}

		// Get authorization headers using supplier ID.
		return $this->get_authorization_headers( $supplier['id'] );
	}
}
