<?php

namespace App\Patient\Entity;

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

/** A logged message/communication with a patient (the «پیام‌ها» tab). */
#[ORM\Entity(repositoryClass: PatientMessageRepository::class)]
#[ORM\Table(name: 'patient_messages')]
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_patient_messages_entity')]
#[ORM\Index(columns: ['record_id'], name: 'idx_patient_messages_record')]
class PatientMessage
{
    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: 'text')]
    private string $body;

    /** Channel: sms | note | call | email … */
    #[ORM\Column(type: 'string', length: 20)]
    private string $channel = 'sms';

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

    public function __construct(PatientRecord $record, string $body, string $channel = 'sms')
    {
        $this->uuid      = Uuid::v4()->toRfc4122();
        $this->record    = $record;
        $this->assignTenantPair($record->getEntityType(), $record->getEntityId());
        $this->body      = $body;
        $this->channel   = $channel;
        $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 toArray(): array
    {
        return [
            'uuid'       => $this->uuid,
            'body'       => $this->body,
            'channel'    => $this->channel,
            'created_at' => $this->createdAt,
        ];
    }
}
