<?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\Shipment\Validator;

use InPost\International\Api\Shipment\Model\Parcel\WeightUnit;
use InPost\International\Shipment\DTO\Weight;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\LessThanOrEqual;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

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

final class ParcelWeightValidator extends ConstraintValidator
{
    /**
     * @const global maximum parcel weight
     */
    private const MAX_WEIGHT_KG = 30.;

    public function validate($value, Constraint $constraint): void
    {
        if (!$constraint instanceof ParcelWeight) {
            throw new UnexpectedTypeException($constraint, ParcelWeight::class);
        }

        if (null === $value) {
            return;
        }

        if (!$value instanceof Weight) {
            throw new UnexpectedTypeException($value, Weight::class);
        }

        $unit = $value->getUnit() ?? WeightUnit::getDefault();
        $weight = (float) $value->getAmount();
        $max = WeightUnit::getDefault()->convert(self::MAX_WEIGHT_KG, $unit);

        $context = $this->context;
        $validator = $context->getValidator()->inContext($context);

        $validator->atPath('weight')->validate($weight, new LessThanOrEqual($max), Constraint::DEFAULT_GROUP);
    }
}
