<?php

namespace App\Models;

use App\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Asset extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'category_id',
        'name',
        'serial_number',
        'purchase_date',
        'warranty_expiry',
        'condition',
        'status',
    ];

    protected $appends = [
        'purchase_date_formatted',
        'warranty_expiry_formatted',
    ];

    protected function casts(): array
    {
        return [
            'purchase_date' => 'date',
            'warranty_expiry' => 'date',
        ];
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(AssetCategory::class, 'category_id');
    }

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

    public function currentAssignment(): HasOne
    {
        return $this->hasOne(AssetAssignment::class)->whereNull('returned_at');
    }

    protected function getPurchaseDateFormattedAttribute(): string
    {
        return $this->purchase_date ? $this->purchase_date->format('M d, Y') : '';
    }

    protected function getWarrantyExpiryFormattedAttribute(): string
    {
        return $this->warranty_expiry ? $this->warranty_expiry->format('M d, Y') : '';
    }
}
