<?php

namespace App\Support;

class AttributeValue
{
    /**
     * Normalise a submitted attribute value into a storable scalar.
     *
     * Dynamic-source select/checkbox options arrive as objects (e.g. {id,name,slug,email});
     * the attribute value column is a string, so reduce an array to its name (preferred), id,
     * or a JSON fallback. Multi-select submits a list of those objects — store the list as
     * JSON so it can be parsed back on populate. Scalars pass through unchanged.
     */
    public static function normalise(mixed $value): mixed
    {
        if (is_array($value)) {
            if (array_is_list($value)) {
                return json_encode($value);
            }
            return $value['name'] ?? $value['id'] ?? json_encode($value);
        }

        return $value;
    }
}
