<?php

namespace App\Master\Models;

use Database\Factories\VehicleModelFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;
use Mtc\Crm\Traits\ModelSortAndFilter;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Mtc\MercuryDataModels\Traits\OrderByName;
use Stancl\Tenancy\Database\Concerns\CentralConnection;

class VehicleModel extends Model
{
    use CentralConnection;
    use HasFactory;
    use OrderByName;
    use ModelSortAndFilter;

    /**
     * Table name
     *
     * @var string
     */
    protected $table = 'vehicle_models';

    /**
     * Mass assign columns
     *
     * @var string[]
     */
    protected $fillable = [
        'make_id',
        'name',
        'slug',
        'autotrader_id',
        'cap_id',
        'lcv_cap_id',
        'type',
        'keyloop_id',
        'keyloop_import_enabled',
        'is_current',
    ];

    protected $casts = [
        'keyloop_import_enabled' => 'boolean',
        'is_current' => 'boolean',
    ];

    /**
     * Default attribute values. `is_current` must never be null: it is propagated
     * into the tenant `vehicle_models.is_current` column, which is NOT NULL.
     *
     * @var array<string, mixed>
     */
    protected $attributes = [
        'is_current' => false,
    ];

    #[\Override]
    protected static function boot()
    {
        parent::boot();

        self::saving(function (self $model) {
            $model->ensureSlug();
        });
    }

    /**
     * Model factory
     *
     * @return VehicleModelFactory
     */
    protected static function newFactory()
    {
        return VehicleModelFactory::new();
    }

    /**
     * Relationship with vehicle make this model belongs
     *
     * @return BelongsTo
     */
    public function make(): BelongsTo
    {
        return $this->belongsTo(VehicleMake::class);
    }

    /**
     * ->ofMake($make_id) to specify model make
     *
     * @param Builder $query
     * @param int $make_id
     * @return Builder
     */
    public function scopeOfMake(Builder $query, $make_id)
    {
        return $query->where('make_id', $make_id);
    }

    private function ensureSlug(): void
    {
        if (empty($this->attributes['slug']) || $this->isDirty('name')) {
            $this->attributes['slug'] = Str::slug($this->attributes['name']);
        }
    }
}
