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

final class Flexilay_Woo_Node_Client {

	public static function init() : void {}

	public static function get_signing_secret() : string {
		$secret = trim( Flexilay_Woo_Options::get_install_token() );
		if ( $secret === '' ) {
			$secret = trim( Flexilay_Woo_Options::get_api_key() );
		}
		return $secret;
	}

	public static function sign_query( string $return_to = 'wp-admin' ) {
		$shop   = Flexilay_Woo_Options::get_shop_domain();
		$ts     = time();
		$rt     = (string) $return_to;
		$secret = self::get_signing_secret();

		if ( $secret === '' ) {
			return new WP_Error( 'missing_signing_secret', 'FlexiLay signing secret is not available.', array( 'status' => 400 ) );
		}

		$payload = $shop . '|' . $ts . '|' . $rt;
		$sig     = hash_hmac( 'sha256', $payload, $secret );

		return array(
			'shop'      => $shop,
			'ts'        => $ts,
			'return_to' => $rt,
			'sig'       => $sig,
		);
	}

	public static function request( string $method, string $path, array $args = array(), string $return_to = 'wp-admin' ) : array {
		$api_base = Flexilay_Woo_Options::get_api_base();
		if ( $api_base === '' ) {
			return array( 'ok' => false, 'error' => 'missing_api_base' );
		}

		$method = strtoupper( $method );
		$path   = ltrim( $path, '/' );

		$query = isset( $args['query'] ) && is_array( $args['query'] ) ? $args['query'] : array();
		$body  = isset( $args['body'] ) ? $args['body'] : null;
		$hdrs  = isset( $args['headers'] ) && is_array( $args['headers'] ) ? $args['headers'] : array();

		$hdrs['X-Flexilay-Shop'] = Flexilay_Woo_Options::get_shop_domain();

		$signed = self::sign_query( $return_to );
		if ( is_wp_error( $signed ) ) {
			return array(
				'ok'    => false,
				'error' => $signed->get_error_code(),
				'msg'   => $signed->get_error_message(),
			);
		}
		$query = array_merge( $query, $signed );

		$url = $api_base . '/' . $path;
		if ( ! empty( $query ) ) {
			$url = add_query_arg( $query, $url );
		}

		$req = array(
			'method'  => $method,
			'headers' => $hdrs,
			'timeout' => 25,
		);

		if ( $body !== null ) {
			$req['headers']['Content-Type'] = 'application/json';
			$req['body']                    = is_string( $body ) ? $body : wp_json_encode( $body );
		}

		$resp = wp_remote_request( $url, $req );
		if ( is_wp_error( $resp ) ) {
			return array( 'ok' => false, 'error' => $resp->get_error_message() );
		}

		$code = (int) wp_remote_retrieve_response_code( $resp );
		$raw  = (string) wp_remote_retrieve_body( $resp );

		$data = json_decode( $raw, true );
		if ( json_last_error() === JSON_ERROR_NONE && is_array( $data ) ) {
			$data['_http'] = $code;
			return $data;
		}

		return array(
			'ok'    => false,
			'error' => 'non_json_response',
			'http'  => $code,
			'raw'   => substr( $raw, 0, 500 ),
		);
	}
}
