<?php

namespace App\Resource\Entity;

use App\Doctor\Entity\DoctorAddress;
use App\Resource\Repository\ResourcePoolRepository;
use App\Shared\Tenant\TenantOwnedTrait;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

/**
 * گروهی از منابع که **جایگزین کامل** یکدیگرند: «لیزرهای آلکساندرایت»، «اتاق‌های معاینه».
 *
 * استخر درون یک شعبه است و اعضایش هم‌نوع‌اند. تسک ۰۶ فرض می‌کند هر عضو جایگزین کامل
 * دیگری است؛ اگر عضوی در شعبهٔ دیگری باشد، بیمار در ساختمان اشتباه می‌ایستد.
 */
#[ORM\Entity(repositoryClass: ResourcePoolRepository::class)]
#[ORM\Table(name: 'resource_pools')]
#[ORM\Index(columns: ['entity_type', 'entity_id', 'active'], name: 'idx_pools_tenant')]
#[ORM\Index(columns: ['address_id', 'resource_type_id'], name: 'idx_pools_address')]
class ResourcePool
{
    use TenantOwnedTrait;

    #[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: DoctorAddress::class)]
    #[ORM\JoinColumn(name: 'address_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    private DoctorAddress $address;

    #[ORM\ManyToOne(targetEntity: ResourceType::class)]
    #[ORM\JoinColumn(name: 'resource_type_id', referencedColumnName: 'id', nullable: false, onDelete: 'RESTRICT')]
    private ResourceType $type;

    #[ORM\Column(type: 'string', length: 150)]
    private string $name;

    #[ORM\Column(type: 'boolean', options: ['default' => true])]
    private bool $active = true;

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

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

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

    public function __construct(DoctorAddress $address, ResourceType $type, string $name)
    {
        $this->uuid      = Uuid::v4()->toRfc4122();
        $this->address   = $address;
        $this->type      = $type;
        $this->name      = $name;
        $this->createdAt = time();
        $this->updatedAt = time();
        $this->members   = new ArrayCollection();

        $this->assignTenantPair($address->tenantEntityType(), $address->tenantEntityId());
    }

    public function getId(): ?int               { return $this->id; }
    public function getUuid(): string           { return $this->uuid; }
    public function getAddress(): DoctorAddress { return $this->address; }
    public function getType(): ResourceType     { return $this->type; }
    public function getName(): string           { return $this->name; }
    public function isActive(): bool            { return $this->active; }
    public function getCreatedAt(): int         { return $this->createdAt; }
    public function getUpdatedAt(): int         { return $this->updatedAt; }

    /** @return Collection<int, ResourcePoolMember> */
    public function getMembers(): Collection    { return $this->members; }

    public function setName(string $v): self { $this->name = $v; $this->touch(); return $this; }
    public function setActive(bool $v): self { $this->active = $v; $this->touch(); return $this; }

    public function touch(): void { $this->updatedAt = time(); }

    public function toArray(): array
    {
        return [
            'uuid'         => $this->uuid,
            'name'         => $this->name,
            'address_uuid' => $this->address->getUuid(),
            'address_name' => $this->address->getName(),
            'type_uuid'    => $this->type->getUuid(),
            'type_code'    => $this->type->getCode(),
            'type_name'    => $this->type->getName(),
            'members'      => array_map(
                static fn (ResourcePoolMember $m): array => $m->toArray(),
                $this->members->toArray(),
            ),
            'active'       => $this->active,
            'created_at'   => $this->createdAt,
            'updated_at'   => $this->updatedAt,
        ];
    }
}
