<?php

namespace App\Appointment\Entity;

use App\Clinic\Entity\Clinic;
use App\Doctor\Entity\Doctor;
use App\Shared\Context\EntityContext;
use App\Shared\Tenant\TenantOwnedTrait;
use Doctrine\ORM\Mapping as ORM;
use App\Appointment\Repository\DateOverrideRepository;
use Symfony\Component\Uid\Uuid;

/**
 * استثنای ساعت کاری یک روز خاص. چون خودِ ساعت کاری per-context است، استثنای آن هم
 * per-context است: clinic باید همان clinic برنامهٔ هفتگی متناظر باشد (NULL = شخصی).
 */
#[ORM\Entity(repositoryClass: DateOverrideRepository::class)]
#[ORM\Table(name: 'date_overrides')]
// doctor_id در کلید می‌ماند: چند پزشکِ یک کلینیک هر کدام استثنای روزِ خودشان را دارند.
#[ORM\UniqueConstraint(name: 'uniq_date_override_doctor_tenant_date', columns: ['doctor_id', 'entity_type', 'entity_id', 'date'])]
class DateOverride
{
    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: Doctor::class)]
    #[ORM\JoinColumn(name: 'doctor_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    private Doctor $doctor;

    /** NULL = مطب شخصی پزشک. */
    #[ORM\ManyToOne(targetEntity: Clinic::class)]
    #[ORM\JoinColumn(name: 'clinic_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')]
    private ?Clinic $clinic = null;

    #[ORM\Column(type: 'integer')]
    private int $date;

    #[ORM\Column(type: 'boolean')]
    private bool $active = false;

    #[ORM\Column(type: 'json', nullable: true)]
    private ?array $setting = null;

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

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

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

    public function __construct(Doctor $doctor, int $date, bool $active = false, ?Clinic $clinic = null)
    {
        $this->uuid      = Uuid::v4()->toRfc4122();
        $this->doctor    = $doctor;
        $this->clinic    = $clinic;
        $this->date      = $date;
        $this->active    = $active;
        $this->createdAt = time();
        $this->updatedAt = time();
    }

    public function getId(): ?int       { return $this->id; }
    public function getUuid(): string   { return $this->uuid; }
    public function getDoctor(): Doctor { return $this->doctor; }
    public function getClinic(): ?Clinic { return $this->clinic; }
    public function getDate(): int      { return $this->date; }
    public function isActive(): bool    { return $this->active; }
    public function getSetting(): ?array { return $this->setting; }
    public function getReason(): ?string { return $this->reason; }

    public function setDate(int $v): self     { $this->date = $v; $this->touch(); return $this; }
    public function setActive(bool $v): self  { $this->active = $v; $this->touch(); return $this; }
    public function setSetting(?array $v): self { $this->setting = $v; $this->touch(); return $this; }
    public function setReason(?string $v): self { $this->reason = $v; $this->touch(); return $this; }

    private function touch(): void { $this->updatedAt = time(); }

    public function toArray(): array
    {
        return [
            'uuid'        => $this->uuid,
            'doctor_uuid' => $this->doctor->getUuid(),
            'clinic_uuid' => $this->clinic?->getUuid(),
            'context'     => $this->clinic === null ? 'personal' : 'clinic',
            'date'        => $this->date,
            // نمایش تاریخ باید از این رشته خوانده شود؛ تبدیل timestamp در مرورگر
            // با UTC انجام می‌شود و برای نیمه‌شبِ تهران یک روز عقب می‌افتد.
            'date_string' => date('Y-m-d', $this->date),
            'active'      => $this->active,
            'reason'      => $this->reason,
            'custom_slots' => $this->setting ?? [],
            'created_at'  => $this->createdAt,
        ];
    }
}
