<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Contact;

use CpCreation\VitiCore\Contact\Model\Contact;
use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use Symfony\Contracts\Service\ResetInterface;

final class ContactProvider implements ResetInterface
{
    private bool $resolved = false;

    private ?Contact $contact = null;

    public function __construct(private readonly ContactRepository $contactRepository) {}

    public function getContact(): ?Contact
    {
        if ($this->resolved) {
            return $this->contact;
        }

        $this->resolved = true;
        $contact = $this->contactRepository->findOne();

        return $this->contact = $contact instanceof Contact ? $contact : null;
    }

    public function getBusinessName(): ?string
    {
        $name = $this->getContact()?->getCompany();
        if (null === $name) {
            return null;
        }

        $name = mb_trim($name);

        return '' !== $name ? $name : null;
    }

    public function reset(): void
    {
        $this->resolved = false;
        $this->contact = null;
    }
}
