<?php
/**
 * AJAX endpoints for the scan.
 */

defined( 'ABSPATH' ) || exit;

class TFWA_Ajax {

	public static function init(): void {
		add_action( 'wp_ajax_tfwa_scan_start', array( __CLASS__, 'scan_start' ) );
		add_action( 'wp_ajax_tfwa_scan_step', array( __CLASS__, 'scan_step' ) );
		add_action( 'wp_ajax_tfwa_report', array( __CLASS__, 'report' ) );
	}

	private static function guard(): void {
		check_ajax_referer( 'tfwa_admin' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'forbidden' ), 403 );
		}
	}

	public static function scan_start(): void {
		self::guard();

		$token = TFWA_Scanner::start();

		wp_send_json_success(
			array(
				'total' => TFWA_Scanner::count_documents(),
				'token' => $token,
			)
		);
	}

	public static function scan_step(): void {
		self::guard();

		$token  = isset( $_POST['token'] ) ? sanitize_key( wp_unslash( $_POST['token'] ) ) : '';
		$result = TFWA_Scanner::run_batch( $token );

		if ( ! empty( $result['error'] ) ) {
			wp_send_json_error( array( 'message' => $result['error'] ) );
		}

		wp_send_json_success( $result );
	}

	public static function report(): void {
		self::guard();

		wp_send_json_success( TFWA_Scanner::get_report() );
	}
}
