<?php
/**
 * Activity REST API Controller
 *
 * Provides REST API endpoints for activity logs.
 *
 * @package Sequensy
 * @since 2.0.0
 */

declare(strict_types=1);

namespace Sequensy\Rest;

use Sequensy\Container;
use Sequensy\Storage\ActivityLogger;
use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Class ActivityController
 *
 * REST API controller for activity logs.
 */
class ActivityController extends WP_REST_Controller {

	use RestControllerTrait;

	/**
	 * Activity logger instance.
	 *
	 * @var ActivityLogger
	 */
	private ActivityLogger $logger;

	/**
	 * Factory method for creating controller instance with container.
	 *
	 * @param Container $container Service container instance.
	 * @return self Controller instance.
	 */
	public static function create( Container $container ): self {
		return new self( $container->get( 'logger' ) );
	}

	/**
	 * Constructor.
	 *
	 * @param ActivityLogger|null $logger Optional logger instance.
	 */
	public function __construct( ?ActivityLogger $logger = null ) {
		$this->namespace = 'sequensy/v1';

		// Use provided dependencies or get from container.
		$container    = Container::getInstance();
		$this->logger = $logger ?? $container->get( 'logger' );
	}

	/**
	 * Register REST API routes.
	 */
	public function register_routes(): void {
		// Get activity logs.
		register_rest_route(
			$this->namespace,
			'/activity',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_activity_logs' ),
				'permission_callback' => array( $this, 'permissions_check' ),
				'args'                => $this->get_activity_params(),
			)
		);
	}

	/**
	 * Get activity logs.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response Response object.
	 */
	public function get_activity_logs( WP_REST_Request $request ): WP_REST_Response {
		$filters = array();

		if ( ! empty( $request['workflow_id'] ) ) {
			$filters['workflow_id'] = (int) $request['workflow_id'];
		}

		if ( ! empty( $request['level'] ) ) {
			$filters['level'] = sanitize_text_field( $request['level'] );
		}

		$limit  = ! empty( $request['limit'] ) ? (int) $request['limit'] : 50;
		$offset = ! empty( $request['offset'] ) ? (int) $request['offset'] : 0;

		$logs  = $this->logger->get_logs( $filters, $limit, $offset );
		$total = $this->logger->get_logs_count( $filters );

		$response = rest_ensure_response( $logs );
		$response->header( 'X-WP-Total', (string) $total );

		return $response;
	}

	/**
	 * Get activity log parameters.
	 *
	 * @return array
	 */
	public function get_activity_params(): array {
		return array(
			'workflow_id' => array(
				'description'       => 'Filter by workflow ID',
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
				'validate_callback' => 'rest_validate_request_arg',
			),
			'level'       => array(
				'description'       => 'Filter by log level',
				'type'              => 'string',
				'enum'              => array( 'info', 'warning', 'error', 'critical' ),
				'sanitize_callback' => 'sanitize_text_field',
				'validate_callback' => 'rest_validate_request_arg',
			),
			'limit'       => array(
				'description'       => 'Number of results',
				'type'              => 'integer',
				'default'           => 50,
				'sanitize_callback' => 'absint',
				'validate_callback' => 'rest_validate_request_arg',
			),
			'offset'      => array(
				'description'       => 'Offset for pagination',
				'type'              => 'integer',
				'default'           => 0,
				'sanitize_callback' => 'absint',
				'validate_callback' => 'rest_validate_request_arg',
			),
		);
	}
}
