<?php

namespace WeeConnectPay\Api\Requests;

use WeeConnectPay\Dependencies\Psr\Http\Message\ResponseInterface;
use WeeConnectPay\Api\ApiClient;
use WeeConnectPay\Api\ApiEndpoints;

/**
 * POST /v1/clover/charges/3ds/finalize
 *
 * Tells the WeeConnect API to call Clover's /v1/charges/finalize_payment with
 * the flow_status the browser collected from the executePatch event after
 * either the method or challenge flow completed. The API persists the terminal
 * charge (or relays another interim state on method->challenge escalation).
 *
 * @since 4.2.0
 */
class FinalizeThreeDSChargeRequest extends ApiClient {

	/**
	 * @param string      $chargeId           Clover charge id returned by the initial create/order-charge response.
	 * @param string      $flowStatus         Value of event.detail._3DSStatus from the browser.
	 * @param string|null $cloverOrderUuid    Clover ecom-order UUID. Provided for order-scoped charges; omitted for standalone charges.
	 * @param string|null $savedCredentialUuid The saved-credential UUID reused on the initial charge, if any.
	 * @param bool        $saveCredential     Whether the initial charge requested saving a new credential (subscription path).
	 */
	public function POST(
		string $chargeId,
		string $flowStatus,
		?string $cloverOrderUuid = null,
		?string $savedCredentialUuid = null,
		bool $saveCredential = false
	): ResponseInterface {
		return $this->client->post(
			ApiEndpoints::finalizeThreeDSCharge(),
			self::setOptions( $chargeId, $flowStatus, $cloverOrderUuid, $savedCredentialUuid, $saveCredential )
		);
	}

	/**
	 * @return array<string, mixed>
	 */
	private static function setOptions(
		string $chargeId,
		string $flowStatus,
		?string $cloverOrderUuid,
		?string $savedCredentialUuid,
		bool $saveCredential
	): array {
		return array(
			'form_params' => self::setRequestBody( $chargeId, $flowStatus, $cloverOrderUuid, $savedCredentialUuid, $saveCredential ),
		);
	}

	/**
	 * @return array<string, mixed>
	 */
	private static function setRequestBody(
		string $chargeId,
		string $flowStatus,
		?string $cloverOrderUuid,
		?string $savedCredentialUuid,
		bool $saveCredential
	): array {
		$params = array(
			'charge_id'   => $chargeId,
			'flow_status' => $flowStatus,
		);

		if ( $cloverOrderUuid !== null && $cloverOrderUuid !== '' ) {
			$params['order_uuid'] = $cloverOrderUuid;
		}

		if ( $savedCredentialUuid !== null && $savedCredentialUuid !== '' ) {
			$params['saved_credential'] = $savedCredentialUuid;
		}

		if ( $saveCredential ) {
			$params['save_credential'] = true;
		}

		return $params;
	}
}
