<?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\Support\PreviewStorage;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

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

    public function generate(WP_REST_Request $request) : WP_REST_Response
    {
        $payload = $request->get_json_params();
        $preview = is_string($payload['preview'] ?? null) ? (string) $payload['preview'] : '';

        if ($preview === '' || strpos($preview, 'data:image/') !== 0) {
            return new WP_REST_Response([
                'success' => false,
                'message' => __('No preview image was received.', 'asuka-product-designer'),
            ], 400);
        }

        $stored = (new PreviewStorage())->store($preview, 'apd-preview', [
            'temporary' => true,
            'context' => 'runtime',
        ]);
        if (! $stored['success']) {
            return new WP_REST_Response($stored, 500);
        }

        return new WP_REST_Response([
            'success' => true,
            'message' => __('Preview stored successfully.', 'asuka-product-designer'),
            'previewUrl' => $stored['url'],
            'attachmentId' => $stored['attachmentId'],
        ]);
    }
}
