<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Ferienpass\CoreBundle\Repository\IntegrationConfigRepository;
use Symfony\Bridge\Doctrine\IdGenerator\UuidGenerator;
use Symfony\Bridge\Doctrine\Types\UuidType;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: IntegrationConfigRepository::class)]
class IntegrationConfig
{
    #[ORM\Id]
    #[ORM\Column(type: UuidType::NAME)]
    #[ORM\GeneratedValue(strategy: 'CUSTOM')]
    #[ORM\CustomIdGenerator(class: UuidGenerator::class)]
    private Uuid $id;

    #[ORM\Column(type: 'string', length: 255, unique: true)]
    private string $provider;

    #[ORM\OneToMany(mappedBy: 'integrationConfig', targetEntity: IntegrationCredential::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
    private Collection $credentials;

    #[ORM\Column(type: 'json')]
    private array $config = [];

    public function __construct(string $provider)
    {
        $this->provider = $provider;
        $this->credentials = new ArrayCollection();
    }

    public function getId(): Uuid
    {
        return $this->id;
    }

    public function getProvider(): string
    {
        return $this->provider;
    }

    /**
     * @return Collection<int, IntegrationCredential>
     */
    public function getCredentials(): Collection
    {
        return $this->credentials;
    }

    public function addCredential(IntegrationCredential $credential): self
    {
        if (!$this->credentials->contains($credential)) {
            $this->credentials->add($credential);
            $credential->setIntegrationConfig($this);
        }

        return $this;
    }

    public function removeCredential(IntegrationCredential $credential): self
    {
        if ($this->credentials->removeElement($credential)) {
            // set the owning side to null (unless already changed)
            if ($credential->getIntegrationConfig() === $this) {
                $credential->setIntegrationConfig(null);
            }
        }

        return $this;
    }

    public function getConfig(): array
    {
        return $this->config;
    }

    public function setConfig(array $config): self
    {
        $this->config = $config;

        return $this;
    }
}
