<?php
namespace Bookaro\Controller\Rest;

defined( 'ABSPATH' ) || exit;

use Bookaro\Utils\RateLimiter;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

class ServicesController extends BaseController
{
    public function register_routes(): void
    {
        register_rest_route( $this->namespace, '/listings/(?P<id>\\d+)/services', [
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [ $this, 'get_services' ],
                'permission_callback' => [ $this, 'can_access' ],
            ],
        ] );

        register_rest_route( $this->namespace, '/providers/(?P<id>\\d+)/services', [
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [ $this, 'get_provider_services' ],
                'permission_callback' => [ $this, 'can_view_provider_services' ],
            ],
        ] );
    }

    public function can_access(): bool
    {
        $require_login = (bool) bookaro_get_option( 'require_login', 1 );
        return $require_login ? is_user_logged_in() : true;
    }

    public function can_view_provider_services( WP_REST_Request $request ): bool|\WP_Error
    {
        $auth = $this->require_authenticated( $request, __( 'You must be logged in to view services.', 'mybookaro' ) );
        if ( is_wp_error( $auth ) ) {
            return $auth;
        }

        $provider_id = absint( $request->get_param( 'id' ) );
        if ( $provider_id < 1 ) {
            return new \WP_Error( 'bookaro_invalid_provider', __( 'Invalid provider.', 'mybookaro' ), [ 'status' => 400 ] );
        }

        if ( current_user_can( 'manage_options' ) ) {
            return true;
        }

        if ( function_exists( 'bookaro_user_has_provider_access' ) && bookaro_user_has_provider_access() ) {
            if ( get_current_user_id() === $provider_id ) {
                return true;
            }
        }

        return new \WP_Error(
            'bookaro_forbidden',
            __( 'You do not have permission to view provider services.', 'mybookaro' ),
            [ 'status' => 403 ]
        );
    }

    public function get_services( WP_REST_Request $request ): WP_REST_Response
    {
        $listing_id = absint( $request->get_param( 'id' ) );
        if ( ! $listing_id ) {
            return new WP_REST_Response(
                [ 'message' => __( 'Invalid listing.', 'mybookaro' ) ],
                400
            );
        }

        if ( ! is_user_logged_in() ) {
            $rate_config = apply_filters(
                'bookaro_rate_limit',
                [ 'limit' => 60, 'window' => 60 ],
                'public_services',
                [ 'listing_id' => $listing_id ]
            );
            $limit = isset( $rate_config['limit'] ) ? (int) $rate_config['limit'] : 60;
            $window = isset( $rate_config['window'] ) ? (int) $rate_config['window'] : 60;
            $identifier = RateLimiter::build_identifier( [
                'ip' => RateLimiter::client_ip(),
                'listing' => $listing_id,
            ] );
            $rate = RateLimiter::check( 'public_services', $identifier, $limit, $window );
            if ( ! $rate['allowed'] ) {
                $response = new WP_REST_Response(
                    [ 'message' => __( 'Too many requests. Please try again later.', 'mybookaro' ) ],
                    429
                );
                $response->header( 'Retry-After', (string) $rate['retry_after'] );
                return $response;
            }
        }

        if ( ! bookaro_is_allowed_listing( $listing_id ) ) {
            return new WP_REST_Response(
                [ 'message' => __( 'Listing not supported.', 'mybookaro' ) ],
                403
            );
        }
        if ( function_exists( 'bookaro_is_lite_listing_allowed' ) && ! bookaro_is_lite_listing_allowed( $listing_id ) ) {
            return new WP_REST_Response(
                [ 'message' => __( 'Listing not supported.', 'mybookaro' ) ],
                403
            );
        }

        $services = function_exists( 'bookaro_get_public_services_for_listing' )
            ? bookaro_get_public_services_for_listing( $listing_id )
            : ( function_exists( 'bookaro_get_bookaro_services_for_listing' )
                ? bookaro_get_bookaro_services_for_listing( $listing_id )
                : [] );

        return rest_ensure_response( $services );
    }

    public function get_provider_services( WP_REST_Request $request ): WP_REST_Response|\WP_Error
    {
        $provider_id = absint( $request->get_param( 'id' ) );
        if ( $provider_id < 1 ) {
            return new WP_REST_Response(
                [ 'message' => __( 'Invalid provider.', 'mybookaro' ) ],
                400
            );
        }

        if ( function_exists( 'bookaro_provider_services_allowed' ) && ! bookaro_provider_services_allowed() ) {
            return new \WP_Error( 'bookaro_forbidden', __( 'Provider services are disabled.', 'mybookaro' ), [ 'status' => 403 ] );
        }

        $services = function_exists( 'bookaro_get_bookaro_provider_services_for_provider' )
            ? bookaro_get_bookaro_provider_services_for_provider( $provider_id )
            : [];

        return rest_ensure_response( $services );
    }
}
