<?php
/**
 * Read-only REST endpoints for thresholds.
 *
 * @package StockGuardianPro
 */

declare(strict_types=1);

namespace StockGuardianPro\LowStock\Services;

use StockGuardianPro\LowStock\Plugin;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

\defined('ABSPATH') || exit;

final class RestApiService implements ServiceInterface
{
    public const ROUTE_NAMESPACE = 'woolsn/v1';

    private Plugin $plugin;

    private ThresholdRepository $repository;

    public function __construct(Plugin $plugin)
    {
        $this->plugin     = $plugin;
        $this->repository = new ThresholdRepository($plugin);
    }

    public function register(): void
    {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes(): void
    {
        register_rest_route(
            self::ROUTE_NAMESPACE,
            '/threshold/(?P<product_id>\d+)(?:/(?P<variation_id>\d+))?',
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [$this, 'get_threshold'],
                'permission_callback' => [$this, 'can_view_thresholds'],
                'args'                => [
                    'product_id'   => [
                        'validate_callback' => 'is_numeric',
                    ],
                    'variation_id' => [
                        'validate_callback' => function ($value): bool {
                            return $value === null || is_numeric($value);
                        },
                    ],
                ],
            ]
        );
    }

    public function get_threshold(WP_REST_Request $request)
    {
        $product_id   = (int) $request->get_param('product_id');
        $variation_id = (int) $request->get_param('variation_id');

        $threshold = $this->repository->get_threshold($product_id, $variation_id);

        return new WP_REST_Response(
            [
                'product_id'   => $product_id,
                'variation_id' => $variation_id,
                'threshold'    => $threshold,
            ]
        );
    }

    public function can_view_thresholds(): bool|WP_Error
    {
        if (! current_user_can('manage_woocommerce')) {
            return new WP_Error(
                'woolsn_rest_forbidden',
                __('You do not have permission to view thresholds.', 'stock-guardian-pro'),
                [
                    'status' => 403,
                ]
            );
        }

        return true;
    }
}

