<?php
/**
 * Shared rules for marking a Woo order as exported to Simply.IN (checkout + background).
 *
 * @package Simplyin\Simplyin_W_Plugin\Sync
 */

namespace Simplyin\Simplyin_W_Plugin\Sync;

use WC_Order;

final class SimplyIn_Api_Order_Response {

	/**
	 * Same literal as Presta module (SimplyInOrderSync::createOrder).
	 */
	public static function is_order_already_exists_message( $message ): bool {
		return is_string( $message ) && 'Order already exists' === trim( $message );
	}

	public static function shop_order_number_matches_order( $api_shop_order_number, WC_Order $order ): bool {
		return (string) $api_shop_order_number === (string) $order->get_order_number();
	}

	public static function response_indicates_order_already_exists( $response ): bool {
		return is_object( $response )
			&& isset( $response->message )
			&& self::is_order_already_exists_message( $response->message );
	}

	/**
	 * Whether we should persist SimplyInOrderId from a createdOrder payload (checkout context).
	 * Requires _id; if API sends shopOrderNumber it must match the Woo order number (string-safe).
	 */
	public static function created_order_payload_is_for_this_wc_order( $created_order, WC_Order $order ): bool {
		if ( ! is_object( $created_order ) || ! isset( $created_order->_id ) ) {
			return false;
		}
		if ( ! isset( $created_order->shopOrderNumber ) ) {
			return true;
		}

		return self::shop_order_number_matches_order( $created_order->shopOrderNumber, $order );
	}
}
