<?php

declare(strict_types=1);

namespace FormConnector\API\Endpoints;

use FormConnector\Features\Retry\RetryQueue;

/**
 * Retry Queue REST API endpoints.
 */
class RetryEndpoints {

	private const NAMESPACE = 'fc/v1';

	/**
	 * Register retry queue routes.
	 */
	public static function register(): void {
		register_rest_route(self::NAMESPACE, '/retry', [
			'methods' => \WP_REST_Server::READABLE,
			'callback' => [self::class, 'get_items'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/retry/stats', [
			'methods' => \WP_REST_Server::READABLE,
			'callback' => [self::class, 'get_stats'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/retry/(?P<id>\d+)/cancel', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'cancel_item'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/retry/(?P<id>\d+)/retry', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'retry_item'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/retry/process', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'process_now'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/retry/cleanup', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'cleanup'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/retry/bulk', [
			'methods' => \WP_REST_Server::CREATABLE,
			'callback' => [self::class, 'bulk'],
			'permission_callback' => [self::class, 'permission_check'],
		]);
	}

	public static function permission_check(): bool {
		return current_user_can('manage_options');
	}

	/**
	 * Get retry queue items.
	 */
	public static function get_items(\WP_REST_Request $request): \WP_REST_Response {
		$queue = RetryQueue::get_instance();

		$args = [
			'page'     => (int) ($request->get_param('page') ?? 1),
			'per_page' => (int) ($request->get_param('per_page') ?? 20),
			'status'   => sanitize_text_field($request->get_param('status') ?? ''),
		];

		return new \WP_REST_Response([
			'success' => true,
			'data' => $queue->get_items($args),
		], 200);
	}

	/**
	 * Get retry queue statistics.
	 */
	public static function get_stats(\WP_REST_Request $request): \WP_REST_Response {
		$queue = RetryQueue::get_instance();

		return new \WP_REST_Response([
			'success' => true,
			'data' => $queue->get_stats(),
		], 200);
	}

	/**
	 * Cancel a pending retry.
	 */
	public static function cancel_item(\WP_REST_Request $request): \WP_REST_Response {
		$id = (int) $request->get_param('id');
		$queue = RetryQueue::get_instance();

		if ($queue->cancel($id)) {
			return new \WP_REST_Response([
				'success' => true,
				'message' => __('Retry cancelled.', 'form-connector'),
			], 200);
		}

		return new \WP_REST_Response([
			'success' => false,
			'message' => __('Could not cancel. Item may not be pending.', 'form-connector'),
		], 400);
	}

	/**
	 * Retry a failed item immediately.
	 */
	public static function retry_item(\WP_REST_Request $request): \WP_REST_Response {
		$id = (int) $request->get_param('id');
		$queue = RetryQueue::get_instance();

		if ($queue->retry_now($id)) {
			return new \WP_REST_Response([
				'success' => true,
				'message' => __('Item queued for immediate retry.', 'form-connector'),
			], 200);
		}

		return new \WP_REST_Response([
			'success' => false,
			'message' => __('Failed to queue retry.', 'form-connector'),
		], 400);
	}

	/**
	 * Manually trigger queue processing.
	 */
	public static function process_now(\WP_REST_Request $request): \WP_REST_Response {
		$queue = RetryQueue::get_instance();
		$queue->process_queue();

		return new \WP_REST_Response([
			'success' => true,
			'message' => __('Queue processing triggered.', 'form-connector'),
			'data' => $queue->get_stats(),
		], 200);
	}

	/**
	 * Remove completed / failed / cancelled rows (optionally older than N days;
	 * days=0 clears them all).
	 */
	public static function cleanup(\WP_REST_Request $request): \WP_REST_Response {
		$days    = max(0, (int) ($request->get_param('days') ?? 0));
		$queue   = RetryQueue::get_instance();
		$deleted = $queue->cleanup($days);

		return new \WP_REST_Response([
			'success' => true,
			'message' => sprintf(
				/* translators: %d: number of removed rows */
				__('Removed %d queue entries.', 'form-connector'),
				$deleted
			),
			'data' => ['deleted' => $deleted],
		], 200);
	}

	/**
	 * Bulk retry / cancel a set of queue items.
	 */
	public static function bulk(\WP_REST_Request $request): \WP_REST_Response {
		$ids    = (array) $request->get_param('ids');
		$action = sanitize_text_field($request->get_param('action') ?? '');

		if (!in_array($action, ['retry', 'cancel'], true)) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __('Invalid bulk action.', 'form-connector'),
			], 400);
		}

		$queue = RetryQueue::get_instance();
		$count = 0;
		foreach ($ids as $id) {
			$id = (int) $id;
			if ($id <= 0) {
				continue;
			}
			$ok = $action === 'retry' ? $queue->retry_now($id) : $queue->cancel($id);
			if ($ok) {
				$count++;
			}
		}

		return new \WP_REST_Response([
			'success' => true,
			'message' => sprintf(
				/* translators: 1: action name, 2: number of items */
				__('Bulk %1$s applied to %2$d items.', 'form-connector'),
				$action,
				$count
			),
			'data' => ['affected' => $count],
		], 200);
	}
}
