<?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\Domain\Product\ProductConfigBinder;
use APD\Repositories\ProductConfigRepository;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

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

    public function show(WP_REST_Request $request) : WP_REST_Response
    {
        $productId = absint($request['id']);
        $variationId = absint($request->get_param('variation_id'));
        $configId = (new ProductConfigBinder())->getConfigIdForProduct($productId, $variationId);
        $config = $configId > 0 ? (new ProductConfigRepository())->find($configId) : [];
        if (($config['status'] ?? '') !== 'publish' && ! current_user_can('manage_asuka_designer') && ! current_user_can('manage_options')) {
            $configId = 0;
            $config = [];
        }
        $frontend = $config ? (new ConfigAssembler())->assemble($config, [
            'mode' => 'customer',
            'productId' => $productId,
            'variationId' => $variationId,
        ]) : null;

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