<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\Model;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Site\Account\Model\AccountAddressData;
use CpCreation\VitiCore\Product\Model\ProductPriceGroup;
use CpCreation\VitiCore\User\Model\User;
use Symfony\Component\Validator\Constraints as Assert;

final class ClientCreateData
{
    #[Assert\NotBlank(message: 'security.email.required')]
    #[Assert\Email(message: 'security.email.invalid')]
    public ?string $email = null;

    #[Assert\NotBlank(message: 'This value should not be blank.')]
    public ?string $plainPassword = null;

    public bool $marketingOptIn = false;

    public bool $verified = true;

    public ?ProductPriceGroup $group = null;

    #[Assert\Valid]
    public AccountAddressData $invoiceAddress;

    #[Assert\Valid]
    public AccountAddressData $deliveryAddress;

    public function __construct()
    {
        $this->invoiceAddress = new AccountAddressData();
        $this->deliveryAddress = new AccountAddressData();
    }

    public function applyToUser(User $user): void
    {
        $user->setEmail(null !== $this->email ? mb_strtolower(mb_trim($this->email)) : null);
        $user->setPlainPassword($this->plainPassword);
        $user->setMarketingOptIn($this->marketingOptIn);
        $user->setIsVerified($this->verified);
        $user->setGroup($this->group);
        $user->setDeliveryAddress($this->deliveryAddress->toDeliveryAddress($user->getDeliveryAddress()));
        $user->setInvoiceAddress(
            $this->invoiceAddress->differentAddress
                ? $this->invoiceAddress->toInvoiceAddress($user->getInvoiceAddress())
                : null
        );
    }
}
