<?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\Config\ConfigAssembler;
use APD\Repositories\ProductConfigRepository;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

class ConfigController
{
    public function registerRoutes() : void
    {
        register_rest_route(RestNamespace::NAME, '/config/(?P<id>\d+)', [
            'methods' => 'GET',
            'permission_callback' => [PermissionGuard::class, 'storefrontConfig'],
            'callback' => [$this, 'show'],
        ]);
    }

    public function show(WP_REST_Request $request) : WP_REST_Response
    {
        $id = absint($request['id']);
        $repository = new ProductConfigRepository();
        $config = $repository->find($id);
        if ($config === []) {
            return new WP_REST_Response([
                'success' => false,
                'message' => __('Product configuration not found.', 'asuka-product-designer'),
            ], 404);
        }
        $frontend = (new ConfigAssembler())->assemble($config, []);

        return new WP_REST_Response([
            'success' => true,
            'config' => $frontend,
        ]);
    }
}
