<?php

namespace App\Models;

use App\Traits\Auditable;
use App\Traits\MultiTenantModelTrait;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class Product extends Model implements HasMedia
{
    use SoftDeletes, MultiTenantModelTrait, InteractsWithMedia, Auditable, HasFactory;

    public $table = 'products';

    protected $appends = [
        'product_catalog',
    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    public static $searchable = [
        'name',
        'model',
        'product_version',
        'part_no',
        'mfg_year',
        'manufacturer',
    ];

    protected $fillable = [
        'machine_type_id',
        'name',
        'model',
        'product_version',
        'part_no',
        'mfg_year',
        'manufacturer',
        'description',
        'created_at',
        'updated_at',
        'deleted_at',
        'team_id',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function registerMediaConversions(Media $media = null): void
    {
        $this->addMediaConversion('thumb')->fit('crop', 50, 50);
        $this->addMediaConversion('preview')->fit('crop', 120, 120);
    }

    public function airCompressorAssets()
    {
        return $this->hasMany(Asset::class, 'air_compressor_id', 'id');
    }

    public function machine_type()
    {
        return $this->belongsTo(FusionType::class, 'machine_type_id');
    }

    public function getProductCatalogAttribute()
    {
        return $this->getMedia('product_catalog');
    }

    public function team()
    {
        return $this->belongsTo(Team::class, 'team_id');
    }
}
