<?php

namespace App\Domain\Facility\Models;

use App\Domain\Facility\Enums\ReservationStatus;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class SpaceReservation extends Model
{
    use BelongsToAcademy, HasUuid, Auditable;

    protected $fillable = [
        'academy_id',
        'facility_id',
        'space_layout_id',
        'status',
        'reservation_date',
        'start_time',
        'end_time',
        'segment_ids',
        'reservable_type',
        'reservable_id',
        'title',
        'notes',
        'is_recurring',
        'recurrence_pattern',
        'recurrence_end_date',
        'created_by',
        'cancelled_by',
        'cancelled_at',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'status' => ReservationStatus::class,
            'reservation_date' => 'date',
            'segment_ids' => 'array',
            'is_recurring' => 'boolean',
            'recurrence_end_date' => 'date',
            'cancelled_at' => 'datetime',
            'metadata' => 'array',
        ];
    }

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

    public function layout(): BelongsTo
    {
        return $this->belongsTo(SpaceLayout::class, 'space_layout_id');
    }

    public function reservable(): MorphTo
    {
        return $this->morphTo();
    }

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

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

    public function isConfirmed(): bool
    {
        return $this->status === ReservationStatus::Confirmed;
    }

    public function isCancelled(): bool
    {
        return $this->status === ReservationStatus::Cancelled;
    }

    public function scopeConfirmed($query)
    {
        return $query->where('status', ReservationStatus::Confirmed);
    }

    public function scopeForDate($query, string $date)
    {
        return $query->where('reservation_date', $date);
    }

    public function scopeOverlapping($query, string $startTime, string $endTime)
    {
        return $query->where('start_time', '<', $endTime)
                     ->where('end_time', '>', $startTime);
    }
}
