<?php

namespace Fotogenic_AI;

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

/**
 * Canonical result delivery and removal routes for Universal Studio.
 */
final class Rest_Studio_Results {
	private Service_Generate_Save $save_service;
	private Service_Generate_Remove $remove_service;

	public function __construct( Service_Generate_Save $save_service, Service_Generate_Remove $remove_service ) {
		$this->save_service   = $save_service;
		$this->remove_service = $remove_service;
	}

	public function register_routes( Rest_Router $router ): void {
		$router->register_route(
			'fotogenic-ai/v1',
			'/studio/results/apply',
			[
				'methods'             => 'POST',
				'callback'            => [ $this, 'apply' ],
				'permission_callback' => [ $router, 'permissions_generate' ],
				'args'                => $this->identity_args(
					[
						'action' => [
							'type'     => 'string',
							'required' => true,
							'enum'     => [ 'apply_featured', 'apply_gallery', 'apply_both', 'add_selected_to_gallery', 'add_all_to_gallery' ],
						],
					]
				),
			]
		);
		$router->register_route(
			'fotogenic-ai/v1',
			'/studio/results/remove',
			[
				'methods'             => 'POST',
				'callback'            => [ $this, 'remove' ],
				'permission_callback' => [ $router, 'permissions_generate' ],
				'args'                => $this->identity_args(),
			]
		);
	}

	/** @return \WP_REST_Response|\WP_Error */
	public function apply( \WP_REST_Request $request ) {
		$not_ready = $this->migration_error();
		if ( is_wp_error( $not_ready ) ) {
			return $not_ready;
		}
		$payload = Rest_Result_Request_Decoder::decode( $request, true, 10 );
		if ( is_wp_error( $payload ) ) {
			return $payload;
		}

		return rest_ensure_response( $this->save_service->apply( $payload, get_current_user_id() ) );
	}

	/** @return \WP_REST_Response|\WP_Error */
	public function remove( \WP_REST_Request $request ) {
		$not_ready = $this->migration_error();
		if ( is_wp_error( $not_ready ) ) {
			return $not_ready;
		}
		$payload = Rest_Result_Request_Decoder::decode( $request, false, 1 );
		if ( is_wp_error( $payload ) ) {
			return $payload;
		}

		return rest_ensure_response( $this->remove_service->remove( $payload, get_current_user_id() ) );
	}

	private function identity_args( array $additional = [] ): array {
		return array_merge(
			[
				'runId'         => [
					'type'      => 'string',
					'required'  => true,
					'minLength' => 1,
					'maxLength' => 64,
				],
				'requestId'     => [
					'type'              => 'string',
					'required'          => true,
					'validate_callback' => static fn( $value ): bool => is_string( $value ) && wp_is_uuid( strtolower( trim( $value ) ) ),
				],
				'workflow'      => [
					'type'     => 'string',
					'required' => true,
					'enum'     => [ 'product_images', 'campaign_set', 'increase_resolution' ],
				],
				'sourceType'    => [
					'type'     => 'string',
					'required' => true,
					'enum'     => [ 'product', 'media', 'post', 'page' ],
				],
				'scope'         => [
					'type'     => 'string',
					'required' => true,
					'enum'     => [ 'single', 'bulk' ],
				],
				'subjectId'     => [
					'type'     => 'integer',
					'required' => true,
					'minimum'  => 1,
				],
				'attachmentIds' => [
					'type'     => 'array',
					'required' => true,
					'minItems' => 1,
					'maxItems' => 10,
					'items'    => [
						'type'    => 'integer',
						'minimum' => 1,
					],
				],
				'bulkRunUuid'   => [
					'type'              => 'string',
					'validate_callback' => static fn( $value ): bool => is_string( $value ) && wp_is_uuid( strtolower( trim( $value ) ) ),
				],
				'bulkItemId'    => [
					'type'    => 'integer',
					'minimum' => 1,
				],
			],
			$additional
		);
	}

	private function migration_error(): ?\WP_Error {
		$migration = Universal_Data_Migration::instance();
		return $migration->is_ready() ? null : $migration->readiness_error();
	}
}
