<?php

declare(strict_types=1);

namespace App\Entity;

use ApiPlatform\Doctrine\Orm\Filter\OrderFilter;
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
use ApiPlatform\Metadata\ApiFilter;
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\Filter\MultiSearchFilter;
use App\Repository\ComposantRepository;
use App\State\ComposantProcessor;
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;

#[UniqueEntity(fields: ['reference'], message: 'Un composant avec cette référence existe déjà.')]
#[ORM\Entity(repositoryClass: ComposantRepository::class)]
#[ORM\Table(name: 'composants')]
#[ORM\HasLifecycleCallbacks]
#[ApiFilter(SearchFilter::class, properties: ['name' => 'ipartial', 'reference' => 'ipartial', 'typeComposant' => 'exact', 'typeComposant.name' => 'ipartial'])]
#[ApiFilter(MultiSearchFilter::class, properties: ['name', 'reference'])]
#[ApiFilter(OrderFilter::class, properties: ['name', 'createdAt'])]
#[ApiResource(
    description: 'Composants du catalogue. Un composant représente un élément fonctionnel rattaché à une machine, avec un type, des fournisseurs 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')", processor: ComposantProcessor::class),
        new Put(security: "is_granted('ROLE_GESTIONNAIRE')"),
        new Patch(security: "is_granted('ROLE_GESTIONNAIRE')"),
        new Delete(security: "is_granted('ROLE_GESTIONNAIRE')"),
    ],
    normalizationContext: ['groups' => ['composant:read']],
    paginationClientItemsPerPage: true,
    paginationMaximumItemsPerPage: 200
)]
class Composant
{
    use CuidEntityTrait;

    #[ORM\Id]
    #[ORM\Column(type: Types::STRING, length: 36)]
    #[Groups(['composant:read', 'document:list'])]
    private ?string $id = null;

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

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

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

    #[ORM\Column(type: Types::TEXT, nullable: true)]
    #[Groups(['composant:read'])]
    private ?string $description = null;

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

    #[ORM\ManyToOne(targetEntity: ModelType::class, inversedBy: 'composants')]
    #[ORM\JoinColumn(name: 'typeComposantId', referencedColumnName: 'id', nullable: true)]
    #[Groups(['composant:read'])]
    private ?ModelType $typeComposant = null;

    #[ORM\ManyToOne(targetEntity: Product::class, inversedBy: 'composants')]
    #[ORM\JoinColumn(name: 'productId', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
    #[Groups(['composant:read'])]
    private ?Product $product = null;

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

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

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

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

    /**
     * @var Collection<int, ComposantPieceSlot>
     */
    #[ORM\OneToMany(targetEntity: ComposantPieceSlot::class, mappedBy: 'composant', cascade: ['persist', 'remove'], orphanRemoval: true)]
    #[ORM\OrderBy(['position' => 'ASC'])]
    private Collection $pieceSlots;

    /**
     * @var Collection<int, ComposantSubcomponentSlot>
     */
    #[ORM\OneToMany(targetEntity: ComposantSubcomponentSlot::class, mappedBy: 'composant', cascade: ['persist', 'remove'], orphanRemoval: true)]
    #[ORM\OrderBy(['position' => 'ASC'])]
    private Collection $subcomponentSlots;

    /**
     * @var Collection<int, ComposantProductSlot>
     */
    #[ORM\OneToMany(targetEntity: ComposantProductSlot::class, mappedBy: 'composant', cascade: ['persist', 'remove'], orphanRemoval: true)]
    #[ORM\OrderBy(['position' => 'ASC'])]
    private Collection $productSlots;

    /**
     * Transient — holds the structure payload sent by the frontend during creation.
     * Not mapped to any column; consumed by ComposantProcessor.
     */
    private ?array $pendingStructure = null;

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

    private bool $skipAudit = false;

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

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

    public function __construct()
    {
        $this->createdAt         = new DateTimeImmutable();
        $this->updatedAt         = new DateTimeImmutable();
        $this->constructeurLinks = new ArrayCollection();
        $this->documents         = new ArrayCollection();
        $this->customFieldValues = new ArrayCollection();
        $this->machineLinks      = new ArrayCollection();
        $this->pieceSlots        = new ArrayCollection();
        $this->subcomponentSlots = new ArrayCollection();
        $this->productSlots      = new ArrayCollection();
    }

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

    public function setName(string $name): static
    {
        $this->name = mb_strtoupper(mb_substr($name, 0, 1)).mb_substr($name, 1);

        return $this;
    }

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

    public function setReference(?string $reference): static
    {
        $this->reference = $reference;

        return $this;
    }

    public function getReferenceAuto(): ?string
    {
        return $this->referenceAuto;
    }

    /**
     * @internal used by ReferenceAutoSubscriber only — not part of the public API
     */
    public function setReferenceAuto(?string $referenceAuto): static
    {
        $this->referenceAuto = $referenceAuto;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(?string $description): static
    {
        $this->description = $description;

        return $this;
    }

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

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

        return $this;
    }

    public function getTypeComposant(): ?ModelType
    {
        return $this->typeComposant;
    }

    public function setTypeComposant(?ModelType $typeComposant): static
    {
        $this->typeComposant = $typeComposant;

        return $this;
    }

    public function getProduct(): ?Product
    {
        return $this->product;
    }

    public function setProduct(?Product $product): static
    {
        $this->product = $product;

        return $this;
    }

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

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

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

    /**
     * @return Collection<int, ComposantPieceSlot>
     */
    public function getPieceSlots(): Collection
    {
        return $this->pieceSlots;
    }

    public function addPieceSlot(ComposantPieceSlot $pieceSlot): static
    {
        if (!$this->pieceSlots->contains($pieceSlot)) {
            $this->pieceSlots->add($pieceSlot);
            $pieceSlot->setComposant($this);
        }

        return $this;
    }

    public function removePieceSlot(ComposantPieceSlot $pieceSlot): static
    {
        $this->pieceSlots->removeElement($pieceSlot);

        return $this;
    }

    /**
     * @return Collection<int, ComposantSubcomponentSlot>
     */
    public function getSubcomponentSlots(): Collection
    {
        return $this->subcomponentSlots;
    }

    public function addSubcomponentSlot(ComposantSubcomponentSlot $subcomponentSlot): static
    {
        if (!$this->subcomponentSlots->contains($subcomponentSlot)) {
            $this->subcomponentSlots->add($subcomponentSlot);
            $subcomponentSlot->setComposant($this);
        }

        return $this;
    }

    public function removeSubcomponentSlot(ComposantSubcomponentSlot $subcomponentSlot): static
    {
        $this->subcomponentSlots->removeElement($subcomponentSlot);

        return $this;
    }

    /**
     * @return Collection<int, ComposantProductSlot>
     */
    public function getProductSlots(): Collection
    {
        return $this->productSlots;
    }

    /**
     * Virtual property — rebuilds the legacy structure JSON from slot tables.
     *
     * @return null|array{pieces: list<array<string, mixed>>, products: list<array<string, mixed>>, subcomponents: list<array<string, mixed>>}
     */
    #[Groups(['composant:read'])]
    public function getStructure(): ?array
    {
        $pieces = [];
        foreach ($this->pieceSlots as $slot) {
            $selectedPiece = $slot->getSelectedPiece();
            $pieces[]      = [
                'slotId'            => $slot->getId(),
                'typePieceId'       => $slot->getTypePiece()?->getId(),
                'selectedPieceId'   => $selectedPiece?->getId(),
                'selectedPieceName' => $selectedPiece?->getName(),
                'quantity'          => $slot->getQuantity(),
                'position'          => $slot->getPosition(),
            ];
        }

        $products = [];
        foreach ($this->productSlots as $slot) {
            $selectedProduct = $slot->getSelectedProduct();
            $products[]      = [
                'slotId'              => $slot->getId(),
                'typeProductId'       => $slot->getTypeProduct()?->getId(),
                'selectedProductId'   => $selectedProduct?->getId(),
                'selectedProductName' => $selectedProduct?->getName(),
                'familyCode'          => $slot->getFamilyCode(),
                'position'            => $slot->getPosition(),
            ];
        }

        $subcomponents = [];
        foreach ($this->subcomponentSlots as $slot) {
            $selectedComposant = $slot->getSelectedComposant();
            $subcomponents[]   = [
                'slotId'                => $slot->getId(),
                'alias'                 => $slot->getAlias(),
                'familyCode'            => $slot->getFamilyCode(),
                'typeComposantId'       => $slot->getTypeComposant()?->getId(),
                'selectedComponentId'   => $selectedComposant?->getId(),
                'selectedComponentName' => $selectedComposant?->getName(),
                'position'              => $slot->getPosition(),
            ];
        }

        if (empty($pieces) && empty($products) && empty($subcomponents)) {
            return null;
        }

        return [
            'pieces'        => $pieces,
            'products'      => $products,
            'subcomponents' => $subcomponents,
        ];
    }

    /**
     * Called by API Platform during denormalization — stores the frontend
     * structure payload so the ComposantProcessor can apply selections.
     */
    public function setStructure(?array $structure): static
    {
        $this->pendingStructure = $structure;

        return $this;
    }

    public function getPendingStructure(): ?array
    {
        return $this->pendingStructure;
    }

    public function clearPendingStructure(): void
    {
        $this->pendingStructure = null;
    }

    public function addProductSlot(ComposantProductSlot $productSlot): static
    {
        if (!$this->productSlots->contains($productSlot)) {
            $this->productSlots->add($productSlot);
            $productSlot->setComposant($this);
        }

        return $this;
    }

    public function removeProductSlot(ComposantProductSlot $productSlot): static
    {
        $this->productSlots->removeElement($productSlot);

        return $this;
    }

    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;
    }
}
