<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Site\Account\Model;

use CpCreation\VitiCore\User\Model\User;
use Symfony\Component\Validator\Constraints as Assert;

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

    public bool $marketingOptIn = false;

    #[Assert\Valid]
    public AccountAddressData $invoiceAddress;

    #[Assert\Valid]
    public AccountAddressData $deliveryAddress;

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

    public static function fromUser(User $user): self
    {
        $data = new self();
        $data->email = $user->getEmail();
        $data->marketingOptIn = $user->isMarketingOptIn();
        $data->invoiceAddress = AccountAddressData::fromAddress($user->getInvoiceAddress());
        $data->deliveryAddress = AccountAddressData::fromAddress($user->getDeliveryAddress());
        $data->invoiceAddress->differentAddress = !$data->invoiceAddress->isEmpty() && !$data->invoiceAddress->equals($data->deliveryAddress);

        return $data;
    }

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