<?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\Runtime;

defined('ABSPATH') || exit;

class RuntimePrintingMethodMapper
{
    public function __construct(private readonly ?RuntimeColorMapper $colorMapper = null)
    {
    }

    public function hydrateColors(array $methods, array $colors) : array
    {
        $colorMapper = $this->colorMapper ?? new RuntimeColorMapper();
        $colorMap = $colorMapper->mapByIdOrValue($colors);

        $normalized = [];
        foreach ($methods as $method) {
            if (! is_array($method) || (isset($method['enabled']) && ! $method['enabled'])) {
                continue;
            }

            $id = sanitize_key((string) ($method['id'] ?? ''));
            $label = sanitize_text_field((string) ($method['label'] ?? ''));
            if ($id === '' || $label === '') {
                continue;
            }

            $colorIds = [];
            if (is_array($method['colorIds'] ?? null)) {
                $colorIds = array_values(array_filter(array_map('sanitize_key', (array) $method['colorIds'])));
            } elseif (is_array($method['palette']['colorIds'] ?? null)) {
                $colorIds = array_values(array_filter(array_map('sanitize_key', (array) $method['palette']['colorIds'])));
            }

            $method['id'] = $id;
            $method['label'] = $label;
            $method['name'] = sanitize_text_field((string) ($method['name'] ?? $label));
            $method['price'] = $this->toFloat($method['price'] ?? 0);
            $method['colorIds'] = $colorIds;
            $method['palette'] = is_array($method['palette'] ?? null) ? (array) $method['palette'] : ['mode' => $colorIds !== [] ? 'restricted' : 'all'];
            $method['palette']['colorIds'] = $colorIds;
            $method['colors'] = $this->resolveColorItems($colorIds, $colorMap);
            $normalized[] = $method;
        }

        return $normalized;
    }

    private function resolveColorItems(array $colorIds, array $colorMap) : array
    {
        if ($colorIds === []) {
            return [];
        }

        $items = [];
        foreach ($colorIds as $id) {
            $id = sanitize_key((string) $id);
            if ($id === '' || ! isset($colorMap[$id])) {
                continue;
            }
            $items[] = $colorMap[$id];
        }

        return $items;
    }

    private function toFloat(mixed $value, float $fallback = 0.0) : float
    {
        if (is_numeric($value)) {
            return (float) $value;
        }
        $value = str_replace(',', '.', trim((string) $value));
        return is_numeric($value) ? (float) $value : $fallback;
    }
}
