<?php

declare(strict_types=1);

namespace CloudXM\NFe\Providers;

use CloudXM\NFe\Bootstrap\Container;
use CloudXM\NFe\Http\Controllers\NFeWebhookController;
use CloudXM\NFe\Rest\InvoiceDocumentController;

/**
 * REST Service Provider
 *
 * Registers REST API routes
 */
class RestServiceProvider
{
    public function __construct(
        private Container $container
    ) {}

    /**
     * Register REST services
     */
    public function register(): void
    {
        // Register InvoiceDocumentController
        $this->container->singleton(InvoiceDocumentController::class, function () {
            return new InvoiceDocumentController(
                $this->container->get(\CloudXM\NFe\Services\ApiClient::class),
                $this->container->get(\CloudXM\NFe\Services\NFeFileStorageService::class)
            );
        });

        // Register NFeWebhookController (Task 13.2)
        $this->container->singleton(NFeWebhookController::class, function () {
            return new NFeWebhookController(
                $this->container->get(\CloudXM\NFe\Services\NFeWebhookProcessorService::class),
                $this->container->get(\CloudXM\NFe\Config\Configuration::class)
            );
        });
    }

    /**
     * Boot REST services
     */
    public function boot(): void
    {
        add_action('rest_api_init', [$this, 'registerRoutes']);
    }

    /**
     * Register REST API routes
     */
    public function registerRoutes(): void
    {
        $documentController = $this->container->get(InvoiceDocumentController::class);

        register_rest_route('cloudxm/v1', '/invoice/(?P<id>[a-zA-Z0-9-]+)/pdf', [
            'methods' => 'GET',
            'callback' => [$documentController, 'downloadPdf'],
            'permission_callback' => '__return_true',
        ]);

        register_rest_route('cloudxm/v1', '/invoice/(?P<id>[a-zA-Z0-9-]+)/xml', [
            'methods' => 'GET',
            'callback' => [$documentController, 'downloadXml'],
            'permission_callback' => '__return_true',
        ]);

        // Task 13.1 — webhook endpoint for async/scheduled invoice callbacks
        $webhookController = $this->container->get(NFeWebhookController::class);

        register_rest_route('cloudxm-nfe/v1', '/webhook', [
            'methods'             => 'POST',
            'callback'            => [$webhookController, 'handle'],
            'permission_callback' => '__return_true',
        ]);
    }
}
