<?php

namespace App\Patient\Entity;

use App\Inventory\Entity\InventoryItem;
use App\Patient\Repository\SessionConsumableRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

/**
 * A consumable (inventory item) used during a patient session. Price is a
 * snapshot of the item's unit price at creation time, mirroring {@see SessionService}.
 */
#[ORM\Entity(repositoryClass: SessionConsumableRepository::class)]
#[ORM\Table(name: 'session_consumables')]
class SessionConsumable
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\Column(type: 'string', length: 36, unique: true)]
    private string $uuid;

    #[ORM\ManyToOne(targetEntity: PatientSession::class, inversedBy: 'consumables')]
    #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
    private PatientSession $session;

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

    #[ORM\Column(name: 'price_rials', type: 'integer')]
    private int $priceRials;

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

    #[ORM\Column(name: 'created_at', type: 'integer')]
    private int $createdAt;

    public function __construct(PatientSession $session, InventoryItem $item, int $quantity = 1)
    {
        $this->uuid       = Uuid::v4()->toRfc4122();
        $this->session    = $session;
        $this->item       = $item;
        $this->priceRials = $item->getPrice();
        $this->quantity   = max(1, $quantity);
        $this->createdAt  = time();
    }

    public function getId(): ?int                 { return $this->id; }
    public function getUuid(): string             { return $this->uuid; }
    public function getSession(): PatientSession  { return $this->session; }
    public function getItem(): InventoryItem      { return $this->item; }
    public function getPriceRials(): int          { return $this->priceRials; }
    public function getQuantity(): int            { return $this->quantity; }
    public function getLineTotalRials(): int      { return $this->priceRials * $this->quantity; }
    public function getCreatedAt(): int           { return $this->createdAt; }

    public function toArray(): array
    {
        return [
            'uuid'                => $this->uuid,
            'inventory_item_uuid' => $this->item->getUuid(),
            'item_name'           => $this->item->getName(),
            'unit'                => $this->item->getUnit(),
            'price_rials'         => $this->priceRials,
            'quantity'            => $this->quantity,
            'line_total_rials'    => $this->getLineTotalRials(),
            'created_at'          => $this->createdAt,
        ];
    }
}
