<?php
/**
 * Credits Endpoint (Week 26)
 *
 * Proxies backend credits status to the WP admin UI without exposing backend_site_api_key to the browser.
 *
 * @package BoostBot
 */

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

class BoostBot_Credits_Endpoint extends BoostBot_Base_Endpoint {

    /**
     * @var string
     */
    protected $rest_base = 'credits';

    public function register() {
        // GET /wp-json/boostbot/v1/credits/status
        $this->register_route(
            '/status',
            'GET',
            array( $this, 'get_status' ),
            array( $this, 'admin_access' )
        );

        // GET /wp-json/boostbot/v1/credits/usage-history?days=30
        $this->register_route(
            '/usage-history',
            'GET',
            array( $this, 'get_usage_history' ),
            array( $this, 'admin_access' )
        );
    }

    public function get_status( $request ) {
        $client_or_error = $this->get_authenticated_client();
        if ( is_wp_error( $client_or_error ) ) {
            $code = $client_or_error->get_error_code();
            $http = ( 'boostbot_backend_missing_site_key' === $code || 'boostbot_backend_key_save_failed' === $code )
                ? 503  // Service Unavailable — recoverable auth issue
                : 500;
            return $this->error( $client_or_error->get_error_message(), $http );
        }

        list( $client, $site_id ) = $client_or_error;

        $status = $client->get_status( (string) $site_id );
        if ( is_wp_error( $status ) ) {
            return $this->error( $status->get_error_message(), 502 ); // Bad Gateway — backend unreachable
        }

        // Feed the low-credits monitor so it has fresh data for admin notices.
        if ( is_array( $status ) && isset( $status['boost_credits']['remaining'] ) ) {
            if ( class_exists( 'BoostBot_Low_Credits_Monitor' ) ) {
                BoostBot_Low_Credits_Monitor::on_credits_fetched( (float) $status['boost_credits']['remaining'] );
            }
        }

        return $this->success( $status );
    }

    public function get_usage_history( $request ) {
        $client_or_error = $this->get_authenticated_client();
        if ( is_wp_error( $client_or_error ) ) {
            $code = $client_or_error->get_error_code();
            $http = ( 'boostbot_backend_missing_site_key' === $code || 'boostbot_backend_key_save_failed' === $code )
                ? 503
                : 500;
            return $this->error( $client_or_error->get_error_message(), $http );
        }

        list( $client, $site_id ) = $client_or_error;

        $days = absint( $request->get_param( 'days' ) );
        if ( $days < 1 || $days > 365 ) {
            $days = 30;
        }

        $history = $client->get_usage_history( (string) $site_id, $days );
        if ( is_wp_error( $history ) ) {
            return $this->error( $history->get_error_message(), 502 );
        }

        return $this->success( $history );
    }

    /**
     * Create and authenticate the backend client.
     *
     * @return array{BoostBot_Credits_Backend_Client, string}|WP_Error Client+site_id pair or error.
     */
    private function get_authenticated_client() {
        $backend_base_url = trim( (string) BoostBot_Settings::get( 'backend_base_url', '' ) );
        if ( empty( $backend_base_url ) ) {
            return new WP_Error( 'boostbot_not_configured', __( 'Credits backend is not configured.', 'boostbot' ) );
        }

        if ( ! class_exists( 'BoostBot_Credits_Backend_Client' ) ) {
            return new WP_Error( 'boostbot_client_missing', __( 'Credits backend client is not available.', 'boostbot' ) );
        }

        $client  = new BoostBot_Credits_Backend_Client();
        $site_id = $client->ensure_site_id();
        if ( is_wp_error( $site_id ) ) {
            return $site_id; // Preserves the original error code (missing_site_key, etc.)
        }

        return array( $client, (string) $site_id );
    }
}


