<?php

declare(strict_types=1);

namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use App\Entity\Trait\CuidEntityTrait;
use App\Repository\MachineRepository;
use DateTimeImmutable;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity(repositoryClass: MachineRepository::class)]
#[ORM\Table(name: 'machines')]
#[ORM\UniqueConstraint(name: 'uniq_machine_name_site', columns: ['name', 'siteId'])]
#[ORM\HasLifecycleCallbacks]
#[UniqueEntity(fields: ['reference'], message: 'Une machine avec cette référence existe déjà.', ignoreNull: true)]
#[UniqueEntity(fields: ['name', 'site'], message: 'Une machine avec ce nom existe déjà sur ce site.')]
#[ApiResource(
    description: 'Machines industrielles rattachées à un site. Chaque machine possède une structure hiérarchique de composants, pièces et produits, ainsi que des champs personnalisés et des documents.',
    operations: [
        new Get(security: "is_granted('ROLE_VIEWER')"),
        new GetCollection(security: "is_granted('ROLE_VIEWER')"),
        new Post(security: "is_granted('ROLE_GESTIONNAIRE')"),
        new Put(security: "is_granted('ROLE_GESTIONNAIRE')"),
        new Patch(security: "is_granted('ROLE_GESTIONNAIRE')"),
        new Delete(security: "is_granted('ROLE_GESTIONNAIRE')"),
    ]
)]
class Machine
{
    use CuidEntityTrait;
    #[ORM\Id]
    #[ORM\Column(type: Types::STRING, length: 36)]
    #[Groups(['document:list'])]
    private ?string $id = null;

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

    #[ORM\Column(type: Types::STRING, length: 255, nullable: true)]
    private ?string $reference = null;

    #[ORM\Column(type: Types::DECIMAL, precision: 10, scale: 2, nullable: true)]
    private ?string $prix = null;

    #[ORM\ManyToOne(targetEntity: Site::class, inversedBy: 'machines')]
    #[ORM\JoinColumn(name: 'siteId', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    #[Assert\NotNull(message: 'Le site est obligatoire.')]
    private ?Site $site = null;

    /**
     * @var Collection<int, MachineConstructeurLink>
     */
    #[ORM\OneToMany(mappedBy: 'machine', targetEntity: MachineConstructeurLink::class, cascade: ['remove'])]
    private Collection $constructeurLinks;

    /**
     * @var Collection<int, MachineComponentLink>
     */
    #[ORM\OneToMany(mappedBy: 'machine', targetEntity: MachineComponentLink::class)]
    private Collection $componentLinks;

    /**
     * @var Collection<int, MachinePieceLink>
     */
    #[ORM\OneToMany(mappedBy: 'machine', targetEntity: MachinePieceLink::class)]
    private Collection $pieceLinks;

    /**
     * @var Collection<int, MachineProductLink>
     */
    #[ORM\OneToMany(mappedBy: 'machine', targetEntity: MachineProductLink::class)]
    private Collection $productLinks;

    /**
     * @var Collection<int, Document>
     */
    #[ORM\OneToMany(mappedBy: 'machine', targetEntity: Document::class)]
    private Collection $documents;

    /**
     * @var Collection<int, CustomField>
     */
    #[ORM\OneToMany(mappedBy: 'machine', targetEntity: CustomField::class, cascade: ['persist', 'remove'])]
    private Collection $customFields;

    /**
     * @var Collection<int, CustomFieldValue>
     */
    #[ORM\OneToMany(mappedBy: 'machine', targetEntity: CustomFieldValue::class)]
    private Collection $customFieldValues;

    #[ORM\Column(type: Types::DATETIME_IMMUTABLE, name: 'createdAt')]
    private DateTimeImmutable $createdAt;

    #[ORM\Column(type: Types::INTEGER, options: ['default' => 1])]
    private int $version = 1;

    /**
     * Transient flag — when true, audit subscribers skip this entity.
     * Used by EntityVersionService::restore() to avoid duplicate AuditLogs.
     */
    private bool $skipAudit = false;

    #[ORM\Column(type: Types::DATETIME_IMMUTABLE, name: 'updatedAt')]
    private DateTimeImmutable $updatedAt;

    public function __construct()
    {
        $now                     = new DateTimeImmutable();
        $this->createdAt         = $now;
        $this->updatedAt         = $now;
        $this->constructeurLinks = new ArrayCollection();
        $this->componentLinks    = new ArrayCollection();
        $this->pieceLinks        = new ArrayCollection();
        $this->productLinks      = new ArrayCollection();
        $this->documents         = new ArrayCollection();
        $this->customFields      = new ArrayCollection();
        $this->customFieldValues = new ArrayCollection();
    }

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

    public function setName(string $name): static
    {
        $this->name = $name;

        return $this;
    }

    public function getReference(): ?string
    {
        return $this->reference;
    }

    public function setReference(?string $reference): static
    {
        $this->reference = (null !== $reference && '' !== trim($reference)) ? $reference : null;

        return $this;
    }

    public function getPrix(): ?string
    {
        return $this->prix;
    }

    public function setPrix(?string $prix): static
    {
        $this->prix = $prix;

        return $this;
    }

    public function getSite(): ?Site
    {
        return $this->site;
    }

    public function setSite(?Site $site): static
    {
        $this->site = $site;

        return $this;
    }

    /**
     * @return Collection<int, CustomField>
     */
    public function getCustomFields(): Collection
    {
        return $this->customFields;
    }

    public function addCustomField(CustomField $customField): static
    {
        if (!$this->customFields->contains($customField)) {
            $this->customFields->add($customField);
            $customField->setMachine($this);
        }

        return $this;
    }

    public function removeCustomField(CustomField $customField): static
    {
        if ($this->customFields->removeElement($customField)) {
            if ($customField->getMachine() === $this) {
                $customField->setMachine(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection<int, MachineConstructeurLink>
     */
    public function getConstructeurLinks(): Collection
    {
        return $this->constructeurLinks;
    }

    /**
     * @return Collection<int, MachineComponentLink>
     */
    public function getComponentLinks(): Collection
    {
        return $this->componentLinks;
    }

    /**
     * @return Collection<int, MachinePieceLink>
     */
    public function getPieceLinks(): Collection
    {
        return $this->pieceLinks;
    }

    /**
     * @return Collection<int, MachineProductLink>
     */
    public function getProductLinks(): Collection
    {
        return $this->productLinks;
    }

    /**
     * @return Collection<int, Document>
     */
    public function getDocuments(): Collection
    {
        return $this->documents;
    }

    /**
     * @return Collection<int, CustomFieldValue>
     */
    public function getCustomFieldValues(): Collection
    {
        return $this->customFieldValues;
    }

    public function getVersion(): int
    {
        return $this->version;
    }

    public function incrementVersion(): static
    {
        ++$this->version;

        return $this;
    }

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

    public function setSkipAudit(bool $skipAudit): static
    {
        $this->skipAudit = $skipAudit;

        return $this;
    }
}
