<?php

namespace App\Models;

use App\Enums\ChargeBasis;
use App\Enums\ReservationStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class BookingSpace extends Model
{
    /**
     * @var list<string>
     */
    protected $fillable = [
        'booking_id',
        'space_id',
        'setup_start',
        'event_start',
        'event_end',
        'breakdown_end',
        'seating_layout',
        'guest_count',
        'unit_price',
        'charge_basis',
        'billable_days',
        'billable_hours',
        'line_total',
        'reservation_status',
        'hold_expires_at',
        'notes',
    ];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'booking_id' => 'integer',
            'space_id' => 'integer',
            'setup_start' => 'datetime',
            'event_start' => 'datetime',
            'event_end' => 'datetime',
            'breakdown_end' => 'datetime',
            'guest_count' => 'integer',
            'unit_price' => 'decimal:2',
            'charge_basis' => ChargeBasis::class,
            'billable_days' => 'integer',
            'billable_hours' => 'integer',
            'line_total' => 'decimal:2',
            'reservation_status' => ReservationStatus::class,
            'hold_expires_at' => 'datetime',
        ];
    }

    /**
     * @return BelongsTo<Booking, $this>
     */
    public function booking(): BelongsTo
    {
        return $this->belongsTo(Booking::class);
    }

    /**
     * @return BelongsTo<Space, $this>
     */
    public function space(): BelongsTo
    {
        return $this->belongsTo(Space::class);
    }

    /**
     * @return HasMany<BookingItem, $this>
     */
    public function items(): HasMany
    {
        return $this->hasMany(BookingItem::class);
    }

    public function isActiveHold(): bool
    {
        return $this->reservation_status === ReservationStatus::Provisional
            && $this->hold_expires_at !== null
            && $this->hold_expires_at->isFuture();
    }

    public function blocksAvailability(): bool
    {
        if ($this->reservation_status === ReservationStatus::Confirmed) {
            return true;
        }

        return $this->isActiveHold();
    }
}
