<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Api\Controllers;

use APD\Api\Middleware\PermissionGuard;
use APD\Api\RestNamespace;
use APD\Domain\Upload\UploadService;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

class UploadController
{
    public function registerRoutes() : void
    {
        register_rest_route(RestNamespace::NAME, '/upload', [
            'methods' => 'POST',
            'permission_callback' => [PermissionGuard::class, 'runtime'],
            'callback' => [$this, 'store'],
        ]);
    }

    public function store(WP_REST_Request $request) : WP_REST_Response
    {
        $payload = (new UploadService())->handle($request);
        $status = isset($payload['_status']) ? (int) $payload['_status'] : 200;
        $retryAfter = isset($payload['_retryAfter']) ? (int) $payload['_retryAfter'] : 0;
        unset($payload['_status'], $payload['_retryAfter']);

        $response = new WP_REST_Response($payload, $status);
        if ($retryAfter > 0) {
            $response->header('Retry-After', (string) $retryAfter);
        }

        return $response;
    }
}
