<?php
/**
 * Admin Action plugin file.
 *
 * @package AMVE\Admin\Actions
 */

use Amve\Ai\Ai_Job;
use Amve\Ai\Ai_Job_Repository;
use Amve\Ai\Ai_Service_Api;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * Change feed status in Ajax.
 *
 * @since 1.0.0
 *
 * @return void
 */
function amve_send_request_to_generate_video_title_from_original_title() {
	check_ajax_referer( 'ajax-nonce', 'nonce' );

	if ( ! isset( $_POST['video_id'], $_POST['partner_id'], $_POST['video_title'] ) ) {
		wp_die( 'Some parameters are missing!' );
	}

	$video_id    = sanitize_text_field( wp_unslash( $_POST['video_id'] ) );
	$partner_id  = sanitize_text_field( wp_unslash( $_POST['partner_id'] ) );
	$video_title = sanitize_text_field( wp_unslash( $_POST['video_title'] ) );

	$ai_service_api = new Ai_Service_Api();
	$api_response   = $ai_service_api->send_request_to_generate_video_title_from_original_title( $video_id, $partner_id, $video_title );

	if ( 'success' !== $api_response->get_code() ) {
		wp_send_json_error(
			array(
				'message' => $api_response->get_message(),
			)
		);
	}

	$ai_job_repository = new Ai_Job_Repository();
	$ai_job            = new Ai_Job(
		$api_response->get_ai_job_id(),
		$api_response->get_ai_job_status(),
		$api_response->get_ai_job_content()
	);
	$ai_job_repository->save_ai_job_in_db( $ai_job );

	wp_send_json_success(
		array(
			'message'   => $api_response->get_message(),
			'status'    => $api_response->get_status(),
			'ai_job_id' => $api_response->get_ai_job_id(),
			'content'   => $api_response->get_ai_job_content(),
		)
	);

	wp_die();
}
add_action( 'wp_ajax_amve_send_request_to_generate_video_title_from_original_title', 'amve_send_request_to_generate_video_title_from_original_title' );
