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

namespace MOWCPS\Common\Abstracts;

use MOWCPS\Common\Constants\Constants;
use MOWCPS\Common\Interfaces\Auth_Strategy_Interface;
use MOWCPS\Common\Services\Logging\Supplier_Logger;

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

/**
 * Abstract Class Auth_Base_Strategy
 *
 * Base class for all authorization strategies
 */
abstract class Auth_Base_Strategy implements Auth_Strategy_Interface {
	/**
	 * Get cached token
	 *
	 * @param int $supplier_id Supplier ID.
	 * @return string|false Token if valid, false if not found or expired
	 */
	protected function get_cached_token( $supplier_id ) {
		$transient_key = 'mowcps_auth_token_' . $supplier_id;
		$cached_data   = get_transient( $transient_key );

		if ( false === $cached_data ) {
			return false;
		}

		// Check if token is expired or will expire within buffer time.
		$buffer_time  = Constants::TOKEN_REFRESH_BUFFER_TIME;
		$current_time = time();

		if ( isset( $cached_data['expires_at'] ) && $current_time >= ( $cached_data['expires_at'] - $buffer_time ) ) {
			// Token is expired or will expire within buffer time, delete it and return false to trigger refresh.
			$time_until_expiry = $cached_data['expires_at'] - $current_time;
			Supplier_Logger::debug( $supplier_id, sprintf( 'Token for supplier %d will expire in %d seconds, refreshing early (buffer: %d seconds)', $supplier_id, $time_until_expiry, $buffer_time ) );
			delete_transient( $transient_key );
			return false;
		}

		return $cached_data['token'];
	}

	/**
	 * Set cached token
	 *
	 * @param int    $supplier_id Supplier ID.
	 * @param string $token Token value.
	 * @param int    $expires_in Expiration time in seconds.
	 * @return void
	 */
	protected function set_cached_token( $supplier_id, $token, $expires_in ) {
		$transient_key = 'mowcps_auth_token_' . $supplier_id;
		$expires_at    = time() + $expires_in;

		$cached_data = array(
			'token'      => $token,
			'expires_at' => $expires_at,
		);

		set_transient( $transient_key, $cached_data, $expires_in );
	}
}
