<?php

namespace App\Models;

use App\Enums\AppointmentStatus;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Appointment extends Model
{
    use BelongsToTenant, HasFactory, SoftDeletes;

    protected $fillable = [
        'tenant_id', 'dentist_id', 'patient_id', 'starts_at', 'ends_at',
        'status', 'source', 'reason', 'notes', 'cancellation_reason', 'created_by',
    ];

    protected function casts(): array
    {
        return [
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
            'status' => AppointmentStatus::class,
            'reminder_24h_sent_at' => 'datetime',
            'reminder_1h_sent_at' => 'datetime',
            'review_request_sent_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(fn (Appointment $a) => $a->uuid ??= (string) Str::uuid());

        // The hard double-booking guard: a unique key occupied while the
        // status holds the slot. Any concurrent insert/update for the same
        // dentist+start hits the unique index and fails at the DB level.
        static::saving(function (Appointment $a) {
            $a->active_slot_key = $a->status->holdsSlot()
                ? $a->dentist_id.'|'.$a->starts_at->format('YmdHi')
                : null;
        });
    }

    public function dentist(): BelongsTo
    {
        return $this->belongsTo(Dentist::class);
    }

    public function patient(): BelongsTo
    {
        return $this->belongsTo(Patient::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function scopeBetween(Builder $q, $from, $to): Builder
    {
        return $q->where('starts_at', '>=', $from)->where('starts_at', '<', $to);
    }

    public function scopeHoldingSlot(Builder $q): Builder
    {
        return $q->whereIn('status', AppointmentStatus::active());
    }
}
