<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Remote data source — thin wrapper around the existing ScholarSync_Remote class.
 *
 * Delegates every call to the scholar-sync.org service, preserving the
 * original paid-mode behaviour exactly.
 *
 * @package ScholarSync
 * @subpackage ScholarSync/includes
 */

require_once SCHOLAR_SYNC_PLUGIN_DIR . '/includes/class-scholar-sync-data-source.php';
require_once SCHOLAR_SYNC_PLUGIN_DIR . '/includes/class-scholar-sync-remote.php';

class ScholarSync_Remote_Source implements ScholarSync_Data_Source {

	public function search_authors( string $query ) {
		$remote = new ScholarSync_Remote( 'author/search' );
		$remote->add_param_to_url( 'q', $query );
		$remote->retrieve_remote_data();
		if ( $remote->has_error() ) {
			return new WP_Error( 'remote_error', $remote->get_error_message() );
		}
		return $remote->get_data();
	}

	public function get_author( string $scholar_id, string $transaction_id = '' ) {
		$remote = new ScholarSync_Remote( 'customer/sync-author' );
		$body = array(
			'author' => $scholar_id,
		);
		if ( $transaction_id !== '' ) {
			$body['transaction_id'] = $transaction_id;
		}
		$remote->retrieve_remote_data_post( $body );
		if ( $remote->has_error() ) {
			$code = $remote->get_error_code();
			if ( $remote->is_upgrade_required() || $code === 'error_exceed_authors' ) {
				return new WP_Error( 'plan_limit_exceeded', $remote->get_error_message(), $remote->get_upgrade_data() );
			}
			if ( $code === 'error_exceed_sync_frequency' ) {
				// Use the code as the WP_Error message so classify_error() can detect it,
				// and carry the full structured data (next_sync_available, limit_type, etc.).
				return new WP_Error( 'plan_limit_exceeded', $code, $remote->get_upgrade_data() );
			}
			if ( $code === 'error_invalid_transaction' || $code === 'error_transaction_expired' ) {
				return new WP_Error( $code, $remote->get_error_message() );
			}
			return new WP_Error( 'remote_error', $remote->get_error_message(), array( 'code' => $code ) );
		}
		return $remote->get_data();
	}

	public function get_sync_status( string $scholar_id ) {
		$remote = new ScholarSync_Remote( 'author/get-sync-status' );
		$remote->add_param_to_url( 'author', $scholar_id );
		$remote->retrieve_remote_data();
		if ( $remote->has_error() ) {
			return new WP_Error( 'remote_error', $remote->get_error_message() );
		}
		return $remote->get_data();
	}
}
