<?php
/**
 * Token Usage API Class
 *
 * REST endpoint for retrieving aggregated token usage statistics.
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.20
 */

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

/**
 * Token Usage REST API handler.
 */
class SmartyPress_AI_Token_Usage_API {

	/**
	 * Constructor — registers REST routes.
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
	}

	/**
	 * Register REST API routes.
	 */
	public function register_rest_routes(): void {
		register_rest_route(
			'smartypress/v1',
			'/token-usage/stats',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_stats' ),
				'permission_callback' => array( $this, 'check_permissions' ),
				'args'                => array(
					'days' => array(
						'type'              => 'integer',
						'default'           => 30,
						'enum'              => array( 7, 14, 30 ),
						'sanitize_callback' => 'absint',
					),
				),
			)
		);
	}

	/**
	 * Handle GET /smartypress/v1/token-usage/stats.
	 *
	 * @param WP_REST_Request $request REST request.
	 * @return WP_REST_Response
	 */
	public function get_stats( WP_REST_Request $request ): WP_REST_Response {
		$days = (int) $request->get_param( 'days' );

		if ( ! in_array( $days, array( 7, 14, 30 ), true ) ) {
			$days = 30;
		}

		$daily   = SmartyPress_AI_Token_Tracker::get_daily_stats( $days );
		$summary = SmartyPress_AI_Token_Tracker::get_summary( $days );

		return rest_ensure_response( array(
			'daily'   => (object) $daily,
			'summary' => $summary,
		) );
	}

	/**
	 * Permission check — admin only.
	 *
	 * @return bool
	 */
	public function check_permissions(): bool {
		return current_user_can( 'manage_options' );
	}
}
