<?php

namespace Modules\Vrc\Entities;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class VrcAppointment extends Model
{
    protected $table = 'vrc_appointments';

    protected $fillable = [
        'business_id', 'location_id', 'erp_customer_id', 'vehicle_id', 'bay_id',
        'assigned_technician_id', 'scheduled_start', 'scheduled_end', 'status',
        'source', 'concern', 'estimated_duration_min', 'repair_order_id', 'notes',
    ];

    protected $casts = [
        'scheduled_start' => 'datetime',
        'scheduled_end'   => 'datetime',
    ];

    public const STATUSES = ['requested', 'confirmed', 'rescheduled', 'checked_in', 'no_show', 'cancelled', 'completed'];

    public function vehicle(): BelongsTo
    {
        return $this->belongsTo(VrcVehicle::class, 'vehicle_id');
    }

    public function bay(): BelongsTo
    {
        return $this->belongsTo(VrcBay::class, 'bay_id');
    }

    public function customer(): BelongsTo
    {
        return $this->belongsTo(\App\Contact::class, 'erp_customer_id');
    }

    /** Statuses that still occupy a bay/time slot for double-booking checks. */
    public function scopeActive(Builder $q): Builder
    {
        return $q->whereNotIn('status', ['cancelled', 'no_show', 'completed']);
    }

    /** Appointments overlapping [$start,$end] on a bay (excluding $ignoreId). */
    public function scopeBayConflicts(Builder $q, int $bayId, string $start, string $end, ?int $ignoreId = null): Builder
    {
        return $q->where('bay_id', $bayId)
            ->active()
            ->when($ignoreId, fn ($w) => $w->where('id', '!=', $ignoreId))
            ->where('scheduled_start', '<', $end)
            ->where(function ($w) use ($start) {
                $w->whereNull('scheduled_end')->orWhere('scheduled_end', '>', $start);
            });
    }
}
