<?php

namespace App\Appointment\Entity;

use App\Doctor\Entity\Doctor;
use Doctrine\ORM\Mapping as ORM;
use App\Appointment\Repository\DateOverrideRepository;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: DateOverrideRepository::class)]
#[ORM\Table(name: 'date_overrides')]
#[ORM\UniqueConstraint(name: 'uniq_date_override_doctor_date', columns: ['doctor_id', 'date'])]
class DateOverride
{
    #[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;

    #[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)
    {
        $this->uuid      = Uuid::v4()->toRfc4122();
        $this->doctor    = $doctor;
        $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 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(),
            'date'        => $this->date,
            'active'      => $this->active,
            'reason'      => $this->reason,
            'custom_slots' => $this->setting ?? [],
            'created_at'  => $this->createdAt,
        ];
    }
}
