<?php

namespace App\Patient\Entity;

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

/** A logged phone call with a patient (the «کال سنتر» tab). */
#[ORM\Entity(repositoryClass: PatientCallRepository::class)]
#[ORM\Table(name: 'patient_calls')]
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_patient_calls_entity')]
#[ORM\Index(columns: ['record_id'], name: 'idx_patient_calls_record')]
class PatientCall
{
    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;

    /** موضوع تماس — short subject (e.g. «پیگیری نوبت»). */
    #[ORM\Column(type: 'string', length: 255)]
    private string $subject;

    /** خلاصه تماس — free-text call summary. */
    #[ORM\Column(type: 'text', nullable: true)]
    private ?string $summary = null;

    /** Call outcome: success | missed. */
    #[ORM\Column(type: 'string', length: 10)]
    private string $outcome = 'success';

    /** When the call happened (Unix seconds); may differ from createdAt. */
    #[ORM\Column(name: 'called_at', type: 'integer')]
    private int $calledAt;

    /** Display name of the staff member who logged the call. */
    #[ORM\Column(type: 'string', length: 120, nullable: true)]
    private ?string $personnel = null;

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

    public function __construct(PatientRecord $record, string $subject, string $outcome = 'success', ?int $calledAt = null)
    {
        $this->uuid      = Uuid::v4()->toRfc4122();
        $this->record    = $record;
        $this->assignTenantPair($record->getEntityType(), $record->getEntityId());
        $this->subject   = $subject;
        $this->outcome   = $outcome;
        $this->calledAt  = $calledAt ?? time();
        $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 setSummary(?string $s): self   { $this->summary = $s; return $this; }
    public function setPersonnel(?string $p): self { $this->personnel = $p; return $this; }

    public function toArray(): array
    {
        return [
            'uuid'       => $this->uuid,
            'subject'    => $this->subject,
            'summary'    => $this->summary,
            'outcome'    => $this->outcome,
            'called_at'  => $this->calledAt,
            'personnel'  => $this->personnel,
            'created_at' => $this->createdAt,
        ];
    }
}
