<?php
/**
 * Cost REST Controller
 *
 * Handles cost tracking operations.
 *
 * @package WP_Agentic_Writer
 */

/**
 * Class WP_Agentic_Writer_Controller_Cost
 *
 * REST controller for cost tracking operations.
 *
 * @since 0.3.0
 */
class WP_Agentic_Writer_Controller_Cost {

    /**
     * Sidebar instance for dependency access.
     *
     * @var WP_Agentic_Writer_Gutenberg_Sidebar
     */
    private $sidebar;

    /**
     * Constructor.
     *
     * @since 0.3.0
     * @param WP_Agentic_Writer_Gutenberg_Sidebar $sidebar Sidebar instance.
     */
    public function __construct( $sidebar ) {
        $this->sidebar = $sidebar;
    }

    /**
     * Handle get cost tracking request.
     *
     * @since 0.1.0
     * @param WP_REST_Request $request REST request.
     * @return WP_REST_Response|WP_Error Response.
     */
    public function handle_get_cost_tracking( $request ) {
        $post_id = $request->get_param( 'post_id' );

        // Check post-specific permission if post_id is provided.
        if ( $post_id > 0 && ! $this->sidebar->check_post_permission( $post_id ) ) {
            return new WP_Error(
                'forbidden',
                __(
                    'You do not have permission to access this post.',
                    'wp-agentic-writer',
                ),
                [ 'status' => 403 ],
            );
        }

        $cost_tracker = WP_Agentic_Writer_Cost_Tracker::get_instance();
        $data          = $cost_tracker->get_frontend_data( $post_id );

        return new WP_REST_Response( $data, 200 );
    }
}
