<?php

namespace Fotogenic_AI;

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

/**
 * Canonical Single-run recovery and polling routes for Universal Studio.
 */
final class Rest_Studio_Run {
	private Service_Generate_Active $active_service;
	private Service_Generate_Poll $poll_service;

	public function __construct( Service_Generate_Active $active_service, Service_Generate_Poll $poll_service ) {
		$this->active_service = $active_service;
		$this->poll_service   = $poll_service;
	}

	public function register_routes( Rest_Router $router ): void {
		$router->register_route(
			'fotogenic-ai/v1',
			'/studio/run/active',
			[
				'methods'             => 'GET',
				'callback'            => [ $this, 'active' ],
				'permission_callback' => [ $router, 'permissions_generate' ],
				'args'                => [
					'sourceType' => [
						'type'     => 'string',
						'required' => true,
						'enum'     => [ 'product', 'media', 'post', 'page' ],
					],
					'subjectId'  => [
						'type'              => 'integer',
						'required'          => true,
						'minimum'           => 1,
						'sanitize_callback' => 'absint',
					],
					'workflow'   => [
						'type'              => 'string',
						'required'          => true,
						'enum'              => [ 'product_images', 'campaign_set', 'increase_resolution' ],
						'sanitize_callback' => 'sanitize_key',
					],
					'requestId'  => [
						'type'              => 'string',
						'required'          => true,
						'validate_callback' => static fn( $value ): bool => is_string( $value ) && wp_is_uuid( strtolower( trim( $value ) ) ),
					],
				],
			]
		);

		$router->register_route(
			'fotogenic-ai/v1',
			'/studio/run/poll',
			[
				'methods'             => 'POST',
				'callback'            => [ $this, 'poll' ],
				'permission_callback' => [ $router, 'permissions_generate' ],
				'args'                => [
					'jobIds'       => [
						'type'        => 'array',
						'required'    => true,
						'minItems'    => 1,
						'maxItems'    => 10,
						'uniqueItems' => true,
						'items'       => [
							'type'      => 'string',
							'minLength' => 1,
							'maxLength' => 64,
						],
					],
					'workflow'     => [
						'type'     => 'string',
						'required' => true,
						'enum'     => [ 'product_images', 'campaign_set', 'increase_resolution' ],
					],
					'requestId'    => [
						'type'              => 'string',
						'required'          => true,
						'validate_callback' => static fn( $value ): bool => is_string( $value ) && wp_is_uuid( strtolower( trim( $value ) ) ),
					],
					'runId'        => [
						'type'      => 'string',
						'required'  => true,
						'minLength' => 1,
						'maxLength' => 64,
					],
					'sourceType'   => [
						'type'     => 'string',
						'required' => true,
						'enum'     => [ 'product', 'media', 'post', 'page' ],
					],
					'subjectId'    => [
						'type'              => 'integer',
						'required'          => true,
						'minimum'           => 1,
						'sanitize_callback' => 'absint',
					],
				],
			]
		);
	}

	/** @return \WP_REST_Response|\WP_Error */
	public function active( \WP_REST_Request $request ) {
		$target     = sanitize_key( (string) $request->get_param( 'sourceType' ) );
		$subject_id = (int) $request->get_param( 'subjectId' );
		if ( ! in_array( $target, [ 'product', 'media', 'post', 'page' ], true ) || $subject_id <= 0 ) {
			return Messages::error( 'invalid_request', 400 );
		}

		$response = $this->active_service->active(
			get_current_user_id(),
			$target,
			$subject_id,
			(string) $request->get_param( 'workflow' ),
			(string) $request->get_param( 'requestId' )
		);

		return rest_ensure_response( $response );
	}

	/** @return \WP_REST_Response|\WP_Error */
	public function poll( \WP_REST_Request $request ) {
		$migration = Universal_Data_Migration::instance();
		if ( ! $migration->is_ready() ) {
			return $migration->readiness_error();
		}
		$response = rest_ensure_response(
			$this->poll_service->poll(
				get_current_user_id(),
				[
					'jobIds'     => $request->get_param( 'jobIds' ),
					'workflow'   => (string) $request->get_param( 'workflow' ),
					'requestId'  => (string) $request->get_param( 'requestId' ),
					'runId'      => (string) $request->get_param( 'runId' ),
					'sourceType' => (string) $request->get_param( 'sourceType' ),
					'subjectId'  => (int) $request->get_param( 'subjectId' ),
				]
			)
		);
		if ( $response instanceof \WP_REST_Response ) {
			$response->header( 'Cache-Control', 'no-store' );
		}

		return $response;
	}
}
