<?php

namespace Fotogenic_AI;

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

final class Service_Generate_Save {
	private Result_Delivery_Coordinator $result_delivery;

    public function __construct( ?ProductMediaWriteAdapter $media_write_adapter ) {
		$this->result_delivery = new Result_Delivery_Coordinator( $media_write_adapter );
    }

    /** @return \WP_REST_Response|\WP_Error */
    public function apply( array $data, int $user_id ) {
        $action = sanitize_key( (string) ( $data['action'] ?? '' ) );
        $attachment_ids = isset( $data['attachmentIds'] ) && is_array( $data['attachmentIds'] )
            ? $data['attachmentIds']
            : [];
        $authorization = ( new Workflow_Response_Factory() )->authorize_mutation( $data, $action, $attachment_ids, $user_id );
        if ( is_wp_error( $authorization ) ) {
            return $authorization;
        }

        $row            = $authorization['row'];
        $attachment_ids = $authorization['attachment_ids'];
		$applied = $this->result_delivery->apply_manual_action( $row, $attachment_ids, $action );
        if ( is_wp_error( $applied ) ) {
            return $applied;
        }

		return rest_ensure_response( $applied );
	}
}
