<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Entity;

use Doctrine\ORM\Mapping as ORM;
use InPost\International\Api\Shipment\Model\Parcel\WeightUnit;
use InPost\International\Shipment\Exception\ParcelException;

if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * @ORM\Embeddable
 */
final class Weight
{
    /**
     * @var float
     *
     * @ORM\Column(type="float")
     */
    private $weight;

    /**
     * @var string
     *
     * @ORM\Column(type="string")
     */
    private $weightUnit;

    public function __construct(float $weight, WeightUnit $unit)
    {
        if (0. > $weight) {
            throw new ParcelException('Weight cannot be negative.');
        }

        $this->weight = $weight;
        $this->weightUnit = $unit->value;
    }

    public function getWeight(): float
    {
        return $this->weight;
    }

    public function getUnit(): WeightUnit
    {
        return WeightUnit::from($this->weightUnit);
    }

    public function __toString(): string
    {
        return sprintf('%s %s', $this->weight, $this->getUnit()->getSymbol());
    }

    public function convert(WeightUnit $toUnit): float
    {
        return $this->getUnit()->convert($this->weight, $toUnit);
    }
}
