<?php

namespace BYDAuto\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

/**
 * Vehicle class.
 *
 * @property int $id
 * @property string $name
 * @property array $alias
 * @property string $spec_id
 */
class Vehicle extends Model
{
    public $timestamps = false;

    protected $table = 'bydauto_vehicles';

    protected $fillable = ['name', 'alias', 'spec_id'];

    protected $casts = ['alias' => 'array'];

    public function dealers()
    {
        return $this->belongsToMany(Dealer::class, 'bydauto_dealer_vehicles', 'vehicle_id', 'dealer_id');
    }

    public static function cachedItems()
    {
        return Cache::remember('BYDAuto:vechicle', 3600, function () {
            return Vehicle::query()->get()->map(fn ($d) => ['id' => $d->id, 'name' => $d->name, 'alias' => $d->alias, 'spec_id' => $d->spec_id]);
        });
    }

    public static function specId($name)
    {
        $items = self::cachedItems();
        $item = $items->first(fn ($d) => in_array($name, $d['alias']) || $d['name'] === $name);
        return $item ? $item['spec_id'] : null;
    }
}
