<?php

namespace Fotogenic_AI;

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

/**
 * Performs a non-billable upstream identity lookup for one durable request.
 */
final class Workflow_Request_Reconciler {
	private Workflow_Upstream_Response_Parser $parser;

	public function __construct( ?Workflow_Upstream_Response_Parser $parser = null ) {
		$this->parser = $parser ?? new Workflow_Upstream_Response_Parser();
	}

	/** @return array<string,mixed>|\WP_Error */
	public function reconcile( string $workflow, string $idempotency_key ) {
		if ( ! Upstream_Request_Identity::is_valid( $idempotency_key ) ) {
			return new \WP_Error(
				'fotogenic_ai_invalid_idempotency_key',
				__( 'The generation request identity is invalid.', 'fotogenic-ai' ),
				[ 'status' => 400, 'not_dispatched' => true ]
			);
		}
		$operation = Workflow_Upstream_Response_Parser::operation_for_workflow( $workflow );
		if ( is_wp_error( $operation ) ) {
			return $operation;
		}

		$response = Api_Client::instance()->request(
			'GET',
			'requests_reconcile',
			[],
			[
				'query_params'    => [ 'operation' => $operation ],
				'idempotency_key' => $idempotency_key,
			]
		);
		if ( is_wp_error( $response ) ) {
			return $response;
		}
		if ( ! is_array( $response ) ) {
			return new \WP_Error(
				'fotogenic_ai_invalid_reconciliation_response',
				__( 'The upstream generation status could not be verified.', 'fotogenic-ai' ),
				[ 'status' => 502 ]
			);
		}

		return $this->parser->parse_reconciliation( $workflow, $response );
	}
}
