<?php

declare(strict_types=1);

namespace App\Entity;

use App\Repository\OrderItemRepository;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: OrderItemRepository::class)]
#[ORM\Table(name: 'order_item')]
class OrderItem
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private null|int $id = null;

    #[ORM\Column(type: 'datetime_immutable')]
    private readonly DateTimeImmutable $createdAt;

    #[ORM\Column(type: 'datetime_immutable')]
    private DateTimeImmutable $updatedAt;

    public function __construct(
        #[ORM\ManyToOne(targetEntity: DrinkType::class, inversedBy: 'orderItems')]
        #[ORM\JoinColumn(name: 'drink_type_id', referencedColumnName: 'id', nullable: false)]
        private DrinkType $drinkType,
        #[ORM\Column(type: 'integer')]
        private int $quantity,
        #[ORM\ManyToOne(targetEntity: Order::class, inversedBy: 'orderItems')]
        #[ORM\JoinColumn(name: 'order_id', referencedColumnName: 'id', nullable: false)]
        private null|Order $order = null,
        null|DateTimeImmutable $createdAt = null,
        null|DateTimeImmutable $updatedAt = null,
    ) {
        $this->createdAt = $createdAt ?? new DateTimeImmutable();
        $this->updatedAt = $updatedAt ?? new DateTimeImmutable();

        // Establish bidirectional relationship
        if ($this->order instanceof Order) {
            $this->order->addOrderItem($this);
        }
    }

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

    public function getOrder(): null|Order
    {
        return $this->order;
    }

    public function setOrder(null|Order $order): self
    {
        // Remove from old order if exists
        if ($this->order instanceof Order && $this->order !== $order) {
            $this->order->removeOrderItem($this);
        }

        // Set new order
        $this->order = $order;

        // Add to new order if not null
        if ($order instanceof Order && !$order->getOrderItems()->contains($this)) {
            $order->addOrderItem($this);
        }

        $this->updateTimestamp();
        return $this;
    }

    public function getDrinkType(): DrinkType
    {
        return $this->drinkType;
    }

    public function setDrinkType(DrinkType $drinkType): self
    {
        $this->drinkType = $drinkType;
        $this->updateTimestamp();
        return $this;
    }

    public function getQuantity(): int
    {
        return $this->quantity;
    }

    public function setQuantity(int $quantity): self
    {
        $this->quantity = $quantity;
        $this->updateTimestamp();
        return $this;
    }

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

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

    private function updateTimestamp(): void
    {
        $this->updatedAt = new DateTimeImmutable();
    }
}
