<?php

namespace App\Patient\Entity;

use App\Patient\Repository\PatientAttachmentRepository;
use App\Shared\Tenant\TenantOwnedTrait;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

/** A file attached to a patient record (the «ضمیمه» tab). */
#[ORM\Entity(repositoryClass: PatientAttachmentRepository::class)]
#[ORM\Table(name: 'patient_attachments')]
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_patient_attachments_entity')]
#[ORM\Index(columns: ['record_id'], name: 'idx_patient_attachments_record')]
class PatientAttachment
{
    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: PatientRecord::class)]
    #[ORM\JoinColumn(name: 'record_id', nullable: false, onDelete: 'CASCADE')]
    private PatientRecord $record;

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

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

    #[ORM\Column(type: 'string', length: 100, nullable: true)]
    private ?string $mime = null;

    #[ORM\Column(type: 'integer', nullable: true)]
    private ?int $size = null;

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

    public function __construct(PatientRecord $record, string $name, string $url, ?string $mime = null, ?int $size = null)
    {
        $this->uuid      = Uuid::v4()->toRfc4122();
        $this->record    = $record;
        $this->assignTenantPair($record->getEntityType(), $record->getEntityId());
        $this->name      = $name;
        $this->url       = $url;
        $this->mime      = $mime;
        $this->size      = $size;
        $this->createdAt = time();
    }

    public function getId(): ?int            { return $this->id; }
    public function getUuid(): string        { return $this->uuid; }
    public function getRecord(): PatientRecord { return $this->record; }
    public function getUrl(): string         { return $this->url; }

    public function toArray(): array
    {
        return [
            'uuid'       => $this->uuid,
            'name'       => $this->name,
            'url'        => $this->url,
            'mime'       => $this->mime,
            'size'       => $this->size,
            'created_at' => $this->createdAt,
        ];
    }
}
