<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;

class Pipeline extends FormEntity
{
    public const TABLE_NAME = 'dealflow_pipelines';

    private ?int $id = null;

    private string $name = '';

    private bool $isDefault = false;

    /**
     * @var Collection<int, DealStage>
     */
    private Collection $stages;

    public function __construct()
    {
        $this->stages = new ArrayCollection();
    }

    /** @param ORM\ClassMetadata<static> $metadata */
    public static function loadMetadata(ORM\ClassMetadata $metadata): void
    {
        $builder = new ClassMetadataBuilder($metadata);

        $builder->setTable(self::TABLE_NAME)
            ->setCustomRepositoryClass(PipelineRepository::class)
            ->addIndex(['is_default'], 'dealflow_pipeline_default_idx');

        $builder->addId();

        $builder->createField('name', 'string')
            ->length(191)
            ->build();

        $builder->createField('isDefault', 'boolean')
            ->columnName('is_default')
            ->build();

        $builder->createOneToMany('stages', DealStage::class)
            ->mappedBy('pipeline')
            ->cascadePersist()
            ->cascadeRemove()
            ->fetchExtraLazy()
            ->build();
    }

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

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

    public function setName(string $name): self
    {
        $this->isChanged('name', $name);
        $this->name = $name;

        return $this;
    }

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

    public function setIsDefault(bool $isDefault): self
    {
        $this->isChanged('isDefault', $isDefault);
        $this->isDefault = $isDefault;

        return $this;
    }

    /**
     * @return Collection<int, DealStage>
     */
    public function getStages(): Collection
    {
        return $this->stages;
    }

    public function addStage(DealStage $stage): self
    {
        if (!$this->stages->contains($stage)) {
            $this->stages->add($stage);
            $stage->setPipeline($this);
        }

        return $this;
    }
}
