<?php

/*
 * This file is part of the Serenity 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 Serenity\CoreBundle\Config\Entity;

use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Serenity\CoreBundle\Config\Repository\ConfigRepository;
use Serenity\CoreBundle\Shared\Aggregate\AggregateRoot;
use Serenity\CoreBundle\Shared\Aggregate\AggregateRootInterface;
use Serenity\CoreBundle\Shared\Common\ConfigInterface;
use Serenity\CoreBundle\Shared\Common\IdentifierTrait;
use Serenity\CoreBundle\Shared\Common\TimestampTrait;
use Serenity\CoreBundle\Shared\Feature\SerenitySaasInterface;
use Serenity\CoreBundle\Shared\Feature\SerenitySaasTrait;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity(repositoryClass: ConfigRepository::class)]
#[ORM\Table(name: 'serenity_core_config')]
#[ORM\UniqueConstraint(name: 'unique_config_per_project', columns: ['name', 'saasIdentifier'], options: ['nulls_not_distinct' => true])]
#[UniqueEntity(fields: ['name', 'saasIdentifier'], message: 'entity.unique.config')]
#[ORM\HasLifecycleCallbacks]
class Config implements AggregateRootInterface, SerenitySaasInterface
{
    use AggregateRoot;
    use IdentifierTrait {
        IdentifierTrait::__construct as private identifierConstruct;
    }

    use SerenitySaasTrait;
    use TimestampTrait;

    #[ORM\Column(type: Types::STRING, length: 255)]
    private string $name;

    #[Assert\Valid]
    #[ORM\Column(type: 'jsonb_document')]
    private ConfigInterface $value;

    public function getName(): string
    {
        return $this->name;
    }

    public function getValue(): ConfigInterface
    {
        return $this->value;
    }

    public function setValue(ConfigInterface $value): void
    {
        $this->value = $value;
        $this->name = $this->value->getName();
        $this->saasIdentifierAutoGenerated = $this->value->isSaasIdentifierConfig();
    }

    public function setSaasIdentifier(?string $saasIdentifier = null): void
    {
        $this->saasIdentifier = $saasIdentifier;
        if (!$this->value->isSaasIdentifierConfig()) {
            $this->saasIdentifier = null;
        }
    }

    public function isSaasIdentifierAutoGenerated(): bool
    {
        return $this->saasIdentifierAutoGenerated;
    }
}
