<?php

declare (strict_types=1);
namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Action\Api\Ucp;

use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Infrastructure\Service\Listener\Items\Hookable\Hookable;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Discovery\DiscoveryResponseBuilder;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Integration\WcPaymentConfigProvider;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\DataProvider\UcpSettingsDataProvider;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Form\Fields\UcpSettingsFormFields;
/**
 * Registers the /.well-known/ucp discovery endpoint via a WordPress rewrite rule.
 *
 * This endpoint cannot use the standard REST API because WordPress does not
 * allow registering routes at /.well-known/ paths.
 */
final class UcpDiscoveryEndpointAction implements Hookable
{
    private const QUERY_VAR = 'ucp_well_known';
    private UcpSettingsDataProvider $settings;
    private WcPaymentConfigProvider $wc_payments;
    private DiscoveryResponseBuilder $builder;
    public function __construct(UcpSettingsDataProvider $settings, WcPaymentConfigProvider $wc_payments, DiscoveryResponseBuilder $builder)
    {
        $this->settings = $settings;
        $this->wc_payments = $wc_payments;
        $this->builder = $builder;
    }
    public function hooks(): void
    {
        add_action('init', [$this, 'add_rewrite_rule']);
        add_filter('query_vars', [$this, 'add_query_var']);
        add_action('template_redirect', [$this, 'handle_request']);
        add_filter('redirect_canonical', [$this, 'disable_canonical_redirect'], 10, 2);
    }
    public function add_rewrite_rule(): void
    {
        add_rewrite_rule('^\.well-known/ucp$', 'index.php?' . self::QUERY_VAR . '=1', 'top');
    }
    /**
     * @param string[] $vars
     * @return string[]
     */
    public function add_query_var(array $vars): array
    {
        $vars[] = self::QUERY_VAR;
        return $vars;
    }
    public function handle_request(): void
    {
        if (!get_query_var(self::QUERY_VAR)) {
            return;
        }
        if (!$this->is_available()) {
            $this->render_not_found();
            return;
        }
        if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] !== 'GET') {
            status_header(405);
            exit;
        }
        $payload = $this->builder->build();
        status_header(200);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($payload, \JSON_UNESCAPED_SLASHES | \JSON_PRETTY_PRINT);
        exit;
    }
    /**
     * Prevents WordPress from redirecting /.well-known/ucp to a canonical URL.
     *
     * @internal
     * @param string|false $redirect_url
     * @param string       $requested_url
     * @return string|false
     */
    public function disable_canonical_redirect($redirect_url, $requested_url)
    {
        if (strpos($requested_url, '.well-known/ucp') !== \false) {
            return \false;
        }
        return $redirect_url;
    }
    private function is_available(): bool
    {
        if (!$this->settings->has(UcpSettingsFormFields::ENABLE_UCP)) {
            return \false;
        }
        $enabled = \filter_var($this->settings->get(UcpSettingsFormFields::ENABLE_UCP), \FILTER_VALIDATE_BOOLEAN);
        return $enabled && $this->wc_payments->is_available();
    }
    private function render_not_found(): void
    {
        global $wp_query;
        $wp_query->set_404();
    }
}
