<?php

namespace Kylin\Logistics\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Kylin\Logistics\Enums\VehicleStatus;
use Kylin\Logistics\Enums\VehicleType;

/**
 * 车辆模型
 *
 * 管理运输车辆信息，包括车牌、类型、载重、GPS 设备绑定等。
 *
 * @property string $plate_number      车牌号
 * @property string $vehicle_type      车辆类型
 * @property float  $rated_load        额定载重
 * @property string $status            车辆状态
 * @property string $gps_device_id     GPS 设备ID
 */
class Vehicle extends Model
{
    protected $table = 'kylin_log_vehicles';

    protected $fillable = [
        'plate_number', 'vehicle_type', 'rated_load', 'status',
        'gps_device_id', 'fleet_id', 'inspection_expire', 'insurance_expire',
    ];

    protected $casts = [
        'vehicle_type' => VehicleType::class,
        'status' => VehicleStatus::class,
        'rated_load' => 'decimal:2',
        'inspection_expire' => 'date',
        'insurance_expire' => 'date',
    ];

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

    public function gpsLocations(): HasMany
    {
        return $this->hasMany(GpsLocation::class);
    }

    public function gpsTracks(): HasMany
    {
        return $this->hasMany(GpsTrack::class);
    }

    public function dispatches(): HasMany
    {
        return $this->hasMany(Dispatch::class);
    }

    public function latestLocation(): BelongsTo
    {
        return $this->belongsTo(GpsLocation::class, 'id', 'vehicle_id')
            ->orderByDesc('located_at');
    }

    /**
     * 获取可用车辆
     */
    public static function getAvailable()
    {
        return static::where('status', VehicleStatus::IDLE)->get();
    }
}
