<?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 App\Repository\PieceRepository;
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\Component\Serializer\Attribute\Groups;

#[ORM\Entity(repositoryClass: PieceRepository::class)]
#[ORM\Table(name: 'pieces')]
#[ORM\HasLifecycleCallbacks]
#[ApiFilter(SearchFilter::class, properties: ['name' => 'ipartial', 'reference' => 'ipartial', 'typePiece' => 'exact'])]
#[ApiFilter(OrderFilter::class, properties: ['name', 'createdAt'])]
#[ApiResource(
    normalizationContext: ['groups' => ['piece:read']],
    paginationClientItemsPerPage: true,
    paginationMaximumItemsPerPage: 500
)]
class Piece
{
    #[ORM\Id]
    #[ORM\Column(type: Types::STRING, length: 36)]
    #[Groups(['piece:read'])]
    private ?string $id = null;

    #[ORM\Column(type: Types::STRING, length: 255, unique: true)]
    #[Groups(['piece:read'])]
    private string $name;

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

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

    #[ORM\ManyToOne(targetEntity: ModelType::class, inversedBy: 'pieces')]
    #[ORM\JoinColumn(name: 'typePieceId', referencedColumnName: 'id', nullable: true)]
    #[Groups(['piece:read'])]
    private ?ModelType $typePiece = null;

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

    #[ORM\Column(type: Types::JSON, nullable: true, name: 'productIds')]
    #[Groups(['piece:read'])]
    private ?array $productIds = null;

    /**
     * @var Collection<int, Constructeur>
     */
    #[ORM\ManyToMany(targetEntity: Constructeur::class, inversedBy: 'pieces')]
    #[ORM\JoinTable(
        name: '_PieceConstructeurs',
        joinColumns: [new ORM\JoinColumn(name: 'A', referencedColumnName: 'id', onDelete: 'CASCADE')],
        inverseJoinColumns: [new ORM\InverseJoinColumn(name: 'B', referencedColumnName: 'id', onDelete: 'CASCADE')]
    )]
    #[Groups(['piece:read'])]
    private Collection $constructeurs;

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

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

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

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

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

    public function __construct()
    {
        $this->constructeurs     = new ArrayCollection();
        $this->documents         = new ArrayCollection();
        $this->customFieldValues = new ArrayCollection();
        $this->machineLinks      = new ArrayCollection();
    }

    #[ORM\PrePersist]
    public function setCreatedAtValue(): void
    {
        $now             = new DateTimeImmutable();
        $this->createdAt = $now;
        $this->updatedAt = $now;

        if (null === $this->id) {
            $this->id = $this->generateCuid();
        }
    }

    #[ORM\PreUpdate]
    public function setUpdatedAtValue(): void
    {
        $this->updatedAt = new DateTimeImmutable();
    }

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

    public function setId(string $id): static
    {
        $this->id = $id;

        return $this;
    }

    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 = $reference;

        return $this;
    }

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

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

        return $this;
    }

    public function getTypePiece(): ?ModelType
    {
        return $this->typePiece;
    }

    public function setTypePiece(?ModelType $typePiece): static
    {
        $this->typePiece = $typePiece;

        return $this;
    }

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

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

        if ($product && empty($this->productIds)) {
            $productId        = $product->getId();
            $this->productIds = $productId ? [$productId] : null;
        }

        if (!$product && empty($this->productIds)) {
            $this->productIds = null;
        }

        return $this;
    }

    /**
     * @return string[]
     */
    public function getProductIds(): array
    {
        if (!is_array($this->productIds)) {
            return [];
        }

        return array_values(
            array_filter(
                array_map(
                    static fn ($value) => is_string($value) ? trim($value) : '',
                    $this->productIds,
                ),
                static fn (string $value) => '' !== $value,
            ),
        );
    }

    public function setProductIds(?array $productIds): static
    {
        if (!is_array($productIds)) {
            $this->productIds = null;

            return $this;
        }

        $normalized = array_values(
            array_unique(
                array_filter(
                    array_map(
                        static fn ($value) => is_string($value) ? trim($value) : '',
                        $productIds,
                    ),
                    static fn (string $value) => '' !== $value,
                ),
            ),
        );

        $this->productIds = [] === $normalized ? null : $normalized;

        return $this;
    }

    /**
     * @return Collection<int, Constructeur>
     */
    public function getConstructeurs(): Collection
    {
        return $this->constructeurs;
    }

    public function addConstructeur(Constructeur $constructeur): static
    {
        if (!$this->constructeurs->contains($constructeur)) {
            $this->constructeurs->add($constructeur);
        }

        return $this;
    }

    public function removeConstructeur(Constructeur $constructeur): static
    {
        $this->constructeurs->removeElement($constructeur);

        return $this;
    }

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

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

    public function getCreatedAt(): DateTimeImmutable
    {
        return $this->createdAt;
    }

    public function getUpdatedAt(): DateTimeImmutable
    {
        return $this->updatedAt;
    }

    private function generateCuid(): string
    {
        return 'cl'.bin2hex(random_bytes(12));
    }
}
