<?php

namespace App\Appointment\Entity;

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

#[ORM\Entity(repositoryClass: WeeklyScheduleRepository::class)]
#[ORM\Table(name: 'weekly_schedules')]
#[ORM\UniqueConstraint(name: 'idx_weekly_schedules_doctor', columns: ['doctor_id'])]
class WeeklySchedule
{
    public const DAYS = ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday'];

    public const META_KEY = 'meta';
    public const DEFAULT_META = [
        'online_booking_enabled' => true,
        'booking_window_value'   => 1,
        'booking_window_unit'    => 'month',
    ];

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\Column(type: 'string', length: 36, unique: true)]
    private string $uuid;

    #[ORM\OneToOne(targetEntity: Doctor::class)]
    #[ORM\JoinColumn(name: 'doctor_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    private Doctor $doctor;

    #[ORM\Column(type: 'json')]
    private array $setting = [];

    #[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, array $setting)
    {
        $this->uuid      = Uuid::v4()->toRfc4122();
        $this->doctor    = $doctor;
        $this->setting   = $setting;
        $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 getSetting(): array { return $this->setting; }

    public function setSetting(array $setting): self
    {
        $meta = $this->setting[self::META_KEY] ?? null;
        unset($setting[self::META_KEY]);
        if ($meta !== null) {
            $setting[self::META_KEY] = $meta;
        }
        $this->setting = $setting;
        $this->updatedAt = time();
        return $this;
    }

    public function getMeta(): array
    {
        return array_merge(self::DEFAULT_META, $this->setting[self::META_KEY] ?? []);
    }

    public function setMeta(array $meta): self
    {
        $current = $this->getMeta();
        $this->setting[self::META_KEY] = [
            'online_booking_enabled' => (bool)($meta['online_booking_enabled'] ?? $current['online_booking_enabled']),
            'booking_window_value'   => max(1, (int)($meta['booking_window_value'] ?? $current['booking_window_value'])),
            'booking_window_unit'    => in_array($meta['booking_window_unit'] ?? null, ['week', 'month'], true)
                ? $meta['booking_window_unit']
                : $current['booking_window_unit'],
        ];
        $this->updatedAt = time();
        return $this;
    }

    public function getDaySchedule(): array
    {
        $schedule = $this->setting;
        unset($schedule[self::META_KEY]);
        return $schedule;
    }

    public function toArray(): array
    {
        return [
            'uuid'       => $this->uuid,
            'doctor_uuid' => $this->doctor->getUuid(),
            'schedule'   => $this->getDaySchedule(),
            'meta'       => $this->getMeta(),
            'created_at' => $this->createdAt,
            'updated_at' => $this->updatedAt,
        ];
    }
}
