<?php
// DESCRIPTION: REST API endpoints for historical data backfill — start, status polling,
// and cancellation of batch export jobs for existing WordPress entities.

namespace SheetWise\Api;

use SheetWise\Backfill\BackfillManager;
use SheetWise\Backfill\BackfillProcessor;
use WP_REST_Server;

class Backfill extends Swise_REST_Controller {

	/**
	 * Route base
	 *
	 * @since 2.0.0
	 *
	 * @var string
	 */
	protected $base = 'backfill';

	/**
	 * Register routes
	 *
	 * @since 2.0.0
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/(?P<id>[\d]+)/start',
			[
				[
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => [ $this, 'start_backfill' ],
					'permission_callback' => [ $this, 'permission_check' ],
				],
			]
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/(?P<id>[\d]+)/status',
			[
				[
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => [ $this, 'get_status' ],
					'permission_callback' => [ $this, 'permission_check' ],
				],
			]
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/(?P<id>[\d]+)/cancel',
			[
				[
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => [ $this, 'cancel_backfill' ],
					'permission_callback' => [ $this, 'permission_check' ],
				],
			]
		);
	}

	/**
	 * Start a backfill job for an integration
	 *
	 * @since 2.0.0
	 *
	 * @param \WP_REST_Request $request
	 *
	 * @return \WP_REST_Response
	 */
	public function start_backfill( $request ) {
		$integration_id = absint( $request->get_param( 'id' ) );
		$integration    = get_post( $integration_id );

		if ( ! $integration ) {
			return rest_ensure_response( [
				'success' => false,
				'message' => __( 'Integration not found.', 'sheet-wise' ),
			] );
		}

		$content = json_decode( $integration->post_content );

		if ( ! $content || empty( $content->source ) ) {
			return rest_ensure_response( [
				'success' => false,
				'message' => __( 'Invalid integration configuration.', 'sheet-wise' ),
			] );
		}

		$hook      = $content->source;
		$processor = new BackfillProcessor();

		if ( ! $processor->supports_backfill( $hook ) ) {
			return rest_ensure_response( [
				'success' => false,
				'message' => __( 'This data source does not support historical export.', 'sheet-wise' ),
			] );
		}

		// Check for existing running backfill
		$manager = new BackfillManager();
		$status  = $manager->get_status( $integration_id );

		if ( $status && $status['status'] === 'running' ) {
			return rest_ensure_response( [
				'success' => false,
				'message' => __( 'A backfill is already running for this integration.', 'sheet-wise' ),
			] );
		}

		// Clean up any previous job state
		$manager->cleanup( $integration_id );

		$state = $manager->start( $integration_id, $hook );

		return rest_ensure_response( [
			'success' => true,
			'message' => sprintf(
				/* translators: %d: number of records */
				__( 'Exporting %d records. This runs in the background.', 'sheet-wise' ),
				$state['total']
			),
			'data'    => $state,
		] );
	}

	/**
	 * Get the status of a backfill job
	 *
	 * @since 2.0.0
	 *
	 * @param \WP_REST_Request $request
	 *
	 * @return \WP_REST_Response
	 */
	public function get_status( $request ) {
		$integration_id = absint( $request->get_param( 'id' ) );

		$manager = new BackfillManager();
		$status  = $manager->get_status( $integration_id );

		if ( ! $status ) {
			return rest_ensure_response( [
				'success' => true,
				'data'    => null,
			] );
		}

		return rest_ensure_response( [
			'success' => true,
			'data'    => $status,
		] );
	}

	/**
	 * Cancel a running backfill job
	 *
	 * @since 2.0.0
	 *
	 * @param \WP_REST_Request $request
	 *
	 * @return \WP_REST_Response
	 */
	public function cancel_backfill( $request ) {
		$integration_id = absint( $request->get_param( 'id' ) );

		$manager = new BackfillManager();
		$result  = $manager->cancel( $integration_id );

		if ( ! $result ) {
			return rest_ensure_response( [
				'success' => false,
				'message' => __( 'No running backfill to cancel.', 'sheet-wise' ),
			] );
		}

		return rest_ensure_response( [
			'success' => true,
			'message' => __( 'Backfill cancelled.', 'sheet-wise' ),
		] );
	}
}
