<?php

namespace App\Appointment\Entity;

use App\Appointment\Repository\AppointmentEventRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

/**
 * تاریخچه‌ی رویدادهای یک نوبت (Timeline). فعلاً فقط رویداد لغو ثبت می‌شود، اما
 * ساختار عمومی است تا رویدادهای بعدی (ایجاد/تأیید/جابه‌جایی) هم قابل افزودن باشند.
 */
#[ORM\Entity(repositoryClass: AppointmentEventRepository::class)]
#[ORM\Table(name: 'appointment_events')]
#[ORM\Index(columns: ['appointment_id', 'created_at'], name: 'idx_appointment_events_appt')]
class AppointmentEvent
{
    public const TYPE_CANCELLED = 'cancelled';

    #[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: Appointment::class)]
    #[ORM\JoinColumn(name: 'appointment_id', nullable: false, onDelete: 'CASCADE')]
    private Appointment $appointment;

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

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

    // کاربرِ عاملِ رویداد (مثلاً لغوکننده)؛ null برای رویدادهای سیستمی.
    #[ORM\Column(name: 'actor_user_id', type: 'integer', nullable: true)]
    private ?int $actorUserId = null;

    // کشِ نام عامل برای نمایش بدون join اضافه.
    #[ORM\Column(name: 'actor_name', type: 'string', length: 191, nullable: true)]
    private ?string $actorName = null;

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

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

    public function __construct(Appointment $appointment, string $type, string $title)
    {
        $this->uuid        = Uuid::v4()->toRfc4122();
        $this->appointment = $appointment;
        $this->type        = $type;
        $this->title       = $title;
        $this->createdAt   = time();
    }

    public function setActor(?int $userId, ?string $name): self { $this->actorUserId = $userId; $this->actorName = $name; return $this; }
    public function setReason(?string $reason): self { $this->reason = $reason; return $this; }

    public function getUuid(): string { return $this->uuid; }

    public function toArray(): array
    {
        return [
            'uuid'       => $this->uuid,
            'type'       => $this->type,
            'title'      => $this->title,
            'actor_name' => $this->actorName,
            'reason'     => $this->reason,
            'created_at' => $this->createdAt,
        ];
    }
}
