<?php

namespace Limb_Chatbot\Includes\Services\Automations;

use Limb_Chatbot\Includes\Data_Objects\Chatbot;
use Limb_Chatbot\Includes\Data_Objects\Dataset;
use Limb_Chatbot\Includes\Services\Dataset_Service;
use Limb_Chatbot\Includes\Services\Helper;
use WP_Post;

use function Symfony\Component\Translation\t;

/**
 * Handles dataset updates when a post is modified.
 *
 * Regenerates datasets for updated posts if auto-update is enabled.
 *
 * @since 1.0.11
 */
class Post_Update_Handler {

	/**
	 * Dataset service.
	 *
	 * @var Dataset_Service
	 * @since 1.0.11
	 */
	private Dataset_Service $dataset_service;

	/**
	 * Constructor.
	 *
	 * @param  Dataset_Service  $dataset_service  Dataset service instance.
	 *
	 * @since 1.0.11
	 */
	public function __construct( Dataset_Service $dataset_service ) {
		$this->dataset_service = $dataset_service;
	}

	/**
	 * Handle post updates by regenerating datasets if auto-update is enabled.
	 *
	 * 1. Tracks changes to post content
	 * 2. Retrieves datasets linked to the updated post
	 * 3. Marks datasets as synced after completion
	 *
	 * @param  int  $post_id  Post ID.
	 * @param  WP_Post  $after  The post object after update.
	 * @param  WP_Post  $before  The post object before update.
	 *
	 * @return void
	 * @since 1.0.11
	 */
	public function handle( int $post_id, WP_Post $after, WP_Post $before ): void {
		try {
			// Check if title, content, or excerpt changed
			$title_changed   = $after->post_title !== $before->post_title;
			$content_changed = $after->post_content !== $before->post_content;
			$excerpt_changed = $after->post_excerpt !== $before->post_excerpt;

			// If none of these critical fields changed, nothing to sync
			if ( ! $title_changed && ! $content_changed && ! $excerpt_changed ) {
				return;
			}

			// Ignore if it was just published
			if ( $before->post_status !== 'publish' && $after->post_status === 'publish' ) {
				return;
			}

			// Ignore auto-saves and revisions
			if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
				return;
			}
			// Step 1: Mark all datasets as not synced
			$datasets = $this->dataset_service->make_post_datasets_not_synced( $after );
			if ( $datasets->is_empty() ) {
				return;
			}

			// Step 2: Regenerate dataset entries for each dataset
			foreach ( $datasets->get() as $dataset ) {
				if ( $dataset instanceof Dataset ) {
					try {
						$chatbot = $dataset->chatbot();
						if ( $chatbot instanceof Chatbot && $chatbot->get_parameter( 'auto_sync_for_post_' . $after->post_type ) ) {
							if ( $title_changed ) {
								$dataset->set_name( $after->post_title );
								$dataset->save();
							}
							$this->dataset_service->regenerate_dataset_entries( $dataset );
						}
					} catch ( \Exception $e ) {
						Helper::log( $e );
					}
				}
			}
		} catch ( \Exception $e ) {
			Helper::log( $e );
		}
	}
}
