<?php
/**
 * PeachPay Square error normalization helpers.
 *
 * @package PeachPay
 */

if ( ! defined( 'PEACHPAY_ABSPATH' ) ) {
	exit;
}

/**
 * Normalizes Square REST and transport errors.
 */
final class PeachPay_Square_Error {

	/**
	 * Normalize a WP_Error transport failure.
	 *
	 * @param WP_Error $error Transport error.
	 * @return array
	 */
	public static function from_wp_error( $error ) {
		return array(
			'status'   => 0,
			'code'     => is_wp_error( $error ) ? $error->get_error_code() : 'transport_error',
			'category' => 'TRANSPORT_ERROR',
			'detail'   => is_wp_error( $error ) ? $error->get_error_message() : __( 'Connection error.', 'peachpay-for-woocommerce' ),
			'message'  => is_wp_error( $error ) ? $error->get_error_message() : __( 'Connection error.', 'peachpay-for-woocommerce' ),
		);
	}

	/**
	 * Normalize Square API response failures.
	 *
	 * @param int   $status HTTP status code.
	 * @param array $data Decoded response data.
	 * @return array
	 */
	public static function from_response( $status, $data ) {
		$first_error = self::first_error( $data );

		return array(
			'status'   => absint( $status ),
			'code'     => isset( $first_error['code'] ) ? (string) $first_error['code'] : 'square_api_error',
			'category' => isset( $first_error['category'] ) ? (string) $first_error['category'] : 'API_ERROR',
			'detail'   => isset( $first_error['detail'] ) ? (string) $first_error['detail'] : __( 'Square API request failed.', 'peachpay-for-woocommerce' ),
			'message'  => isset( $first_error['detail'] ) ? (string) $first_error['detail'] : __( 'Square API request failed.', 'peachpay-for-woocommerce' ),
		);
	}

	/**
	 * Return a buyer-safe message from normalized error data.
	 *
	 * @param array  $error Normalized error.
	 * @param string $fallback Fallback message.
	 * @return string
	 */
	public static function safe_message( $error, $fallback ) {
		$category = isset( $error['category'] ) ? (string) $error['category'] : '';
		$code     = isset( $error['code'] ) ? trim( (string) $error['code'] ) : '';
		$detail   = isset( $error['detail'] ) ? trim( (string) $error['detail'] ) : '';

		if ( 'AUTHENTICATION_ERROR' === $category ) {
			return __( 'Payment is temporarily unavailable. Please try another payment method or contact the store for assistance.', 'peachpay-for-woocommerce' );
		}

		if ( 'PAYMENT_METHOD_ERROR' === $category ) {
			if ( ! empty( $code ) && ! empty( $detail ) ) {
				return $code . ': ' . $detail;
			}

			if ( ! empty( $detail ) ) {
				return $detail;
			}
		}

		return ! empty( $detail ) ? $detail : $fallback;
	}

	/**
	 * Extract first Square error object from API response.
	 *
	 * @param array $data Response body data.
	 * @return array
	 */
	private static function first_error( $data ) {
		if ( ! is_array( $data ) || empty( $data['errors'] ) || ! is_array( $data['errors'] ) || empty( $data['errors'][0] ) || ! is_array( $data['errors'][0] ) ) {
			return array();
		}

		return $data['errors'][0];
	}
}
