<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Asset extends Model
{
    use HasFactory;

    protected $table = 'assets';

    protected $fillable = [
        'id',
        'entity_type',
        'created_time',
        'tenant_id',
        'customer_xid',
        'name',
        'type',
        'label',
        'asset_profile_id',
        'external_id',
        'version',
        'additional_info',
    ];

    protected $casts = [
        'id' => 'string',
        'tenant_id' => 'string',
        'customer_id' => 'string',
        'asset_profile_id' => 'string',
        'external_id' => 'string',
        'additional_info' => 'array',
    ];
    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            // Generate UUIDs only if they are not already provided
            $model->id = $model->id ?? Str::uuid()->toString();
            $model->tenant_id = $model->tenant_id ?? Str::uuid()->toString();
            $model->asset_profile_id = $model->asset_profile_id ?? Str::uuid()->toString();
            $model->external_id = $model->external_id ?? Str::uuid()->toString();
        });
    }

    public function customer()
    {
        return $this->belongsTo(Customer::class, 'customer_xid', 'id');
    }

    public function userLinks()
    {
        return $this->hasMany(UserAssetLink::class, 'asset_id', 'id');
    }

    public function devices()
    {
        return $this->hasMany(Device::class, 'asset_id', 'id');
    }
    public function userAssetLinks()
    {
        return $this->hasMany(UserAssetLink::class, 'asset_id', 'id');
    }
}
