<?php

namespace VendorTasksDokanClickUp\VendorIntegration;

use VendorTasksDokanClickUp\VendorIntegration\VendorTaskState;

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

/**
 * Vendor Deletion Handler
 *
 * Deletes the corresponding ClickUp task when a vendor is removed from the site.
 * Fires on both the Dokan-specific hook and the standard WordPress deleted_user hook.
 *
 * @since 1.1.0
 * @package VendorTasksDokanClickUp
 * @subpackage VendorIntegration
 */
class DeletionHandler {

	/**
	 * Class constructor
	 *
	 * @since 1.1.0
	 */
	public function __construct() {
		// Dokan-specific deletion (vendor removed from Dokan admin)
		add_action( 'dokan_delete_vendor', array( $this, 'on_vendor_deleted' ), 10, 1 );

		// WordPress core fallback (account deletion)
		add_action( 'deleted_user', array( $this, 'on_vendor_deleted' ), 10, 1 );
	}

	/**
	 * Handle vendor deletion
	 *
	 * @since 1.1.0
	 *
	 * @param int $vendor_id Deleted vendor user ID.
	 * @return void
	 */
	public function on_vendor_deleted( int $vendor_id ): void {
		$task_state = new VendorTaskState();
		$task_id    = $task_state->get_task_id( $vendor_id );
		if ( empty( $task_id ) ) {
			return;
		}

		$client = vendor_tasks_dokan_clickup()->get_clickup_client();
		if ( ! $client ) {
			return;
		}

		// Use the ClickUp DELETE endpoint directly via make_request
		$result = $client->delete_task( $task_id );

		if ( is_wp_error( $result ) ) {
			vendor_tasks_dokan_clickup()->log(
				sprintf(
					'Failed to delete ClickUp task %s for deleted vendor ID %d: %s',
					$task_id,
					$vendor_id,
					$result->get_error_message()
				),
				'error'
			);
		} else {
			vendor_tasks_dokan_clickup()->log(
				sprintf(
					'ClickUp task %s deleted for vendor ID %d.',
					$task_id,
					$vendor_id
				),
				'info'
			);
		}

		// Always clean up meta, even if API call failed
		$task_state->clear_task( $vendor_id );

		// Remove from retry queue if present
		( new \VendorTasksDokanClickUp\Queue\PendingQueue() )->dequeue( $vendor_id );
	}
}
