<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Product;

use CpCreation\VitiCore\Product\Model\ProductVariant;

final readonly class ProductVariantSkuResolver
{
    public function resolve(ProductVariant $variant): ?string
    {
        $variantSku = $this->normalize($variant->getSku());
        if (null !== $variantSku) {
            return $variantSku;
        }

        $productSku = $this->normalize($variant->getProduct()?->getSku());
        if (null === $productSku) {
            return null;
        }

        $typeCode = $this->normalize($variant->getType()?->getCode());

        return null === $typeCode ? $productSku : $productSku . '-' . $typeCode;
    }

    private function normalize(?string $value): ?string
    {
        if (null === $value) {
            return null;
        }

        $value = trim($value);

        return '' === $value ? null : $value;
    }
}
