<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Validator;

use Gls\GlsPoland\Consignment\DTO\ServiceDetails;
use Gls\GlsPoland\Translation\TranslatorAwareTrait;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class CompatibleServicesValidator extends ConstraintValidator
{
    use TranslatorAwareTrait;

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

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

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

        if ($value->isShopDelivery() && $value->isShopReturn()) {
            $this->context
                ->buildViolation($this->getTranslator()->trans('ShopDelivery and ShopReturn services are exclusive.', [], 'Modules.Glspoland.Errors'))
                ->addViolation();
        }

        if (
            ($value->isShopDelivery() || $value->isShopReturn()) &&
            ($value->isCashOnDelivery() || $value->isExpressDelivery() || $value->isDocumentReturn())
        ) {
            $message = $this->getTranslator()->trans('#service# service cannot be combined with Cash, ExpressParcel or DocumentReturn services.', [
                '#service#' => $value->isShopDelivery() ? 'ShopDelivery' : 'ShopReturn',
            ], 'Modules.Glspoland.Errors');

            $this->context
                ->buildViolation($message)
                ->addViolation();
        }
    }
}
