<?php

namespace App\ClinicService\Entity;

use App\Inventory\Entity\InventoryItem;
use Doctrine\ORM\Mapping as ORM;

/**
 * یک قلم کالای مصرفیِ مستقل روی یک خدمت: ارجاع به {@see InventoryItem} به‌همراه تعداد.
 *
 * مکمل (نه جایگزین) `ServiceItem::$inventoryPackageId` است؛ یک خدمت می‌تواند هم یک
 * پکیج آماده داشته باشد و هم چند قلم تکی. هم‌شکل {@see \App\Inventory\Entity\InventoryPackageItem}.
 */
#[ORM\Entity]
#[ORM\Table(name: 'service_item_consumables')]
#[ORM\UniqueConstraint(name: 'uniq_service_item_consumable', columns: ['service_item_id', 'item_id'])]
class ServiceItemConsumable
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\ManyToOne(targetEntity: ServiceItem::class, inversedBy: 'consumables')]
    #[ORM\JoinColumn(name: 'service_item_id', nullable: false, onDelete: 'CASCADE')]
    private ServiceItem $serviceItem;

    #[ORM\ManyToOne(targetEntity: InventoryItem::class)]
    #[ORM\JoinColumn(name: 'item_id', nullable: false, onDelete: 'CASCADE')]
    private InventoryItem $item;

    #[ORM\Column(type: 'integer')]
    private int $amount = 1;

    public function __construct(InventoryItem $item, int $amount = 1)
    {
        $this->item   = $item;
        $this->amount = max(1, $amount);
    }

    public function getId(): ?int                { return $this->id; }
    public function getServiceItem(): ServiceItem { return $this->serviceItem; }
    public function getItem(): InventoryItem     { return $this->item; }
    public function getAmount(): int             { return $this->amount; }

    public function setServiceItem(ServiceItem $s): self { $this->serviceItem = $s; return $this; }
    public function setAmount(int $v): self              { $this->amount = max(1, $v); return $this; }

    public function toArray(): array
    {
        return [
            'item_uuid' => $this->item->getUuid(),
            'name'      => $this->item->getName(),
            'unit'      => $this->item->getUnit(),
            'price'     => $this->item->getPrice(),
            'stock'     => $this->item->getStock(),
            'amount'    => $this->amount,
        ];
    }
}
