<?php

namespace App\Patient\Entity;

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

/** A medical examination / note entry on a patient record (the «پرونده پزشکی» tab). */
#[ORM\Entity(repositoryClass: PatientMedicalRecordRepository::class)]
#[ORM\Table(name: 'patient_medical_records')]
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_patient_medical_records_entity')]
#[ORM\Index(columns: ['record_id'], name: 'idx_pmr_record')]
class PatientMedicalRecord
{
    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 $title;

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

    /** Exam date (Unix ts); defaults to creation time. */
    #[ORM\Column(name: 'recorded_at', type: 'integer')]
    private int $recordedAt;

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

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

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

    public function setTitle(string $v): self       { $this->title = $v; return $this; }
    public function setBody(?string $v): self       { $this->body = $v; return $this; }
    public function setRecordedAt(int $v): self     { $this->recordedAt = $v; return $this; }

    public function toArray(): array
    {
        return [
            'uuid'        => $this->uuid,
            'title'       => $this->title,
            'body'        => $this->body,
            'recorded_at' => $this->recordedAt,
            'created_at'  => $this->createdAt,
        ];
    }
}
