<?php

namespace App\Models;

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

class RequestItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'short_name',
        'full_name',
        'display_name',
        'unit',
        'stock',
        'min_stock',
        'image_url',
        'description',
        'is_active',
    ];

    protected $casts = [
        'stock' => 'decimal:2',
        'min_stock' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    public function requests()
    {
        return $this->hasMany(ItemRequest::class);
    }

    public function getImageUrlAttribute($value)
    {
        if (blank($value)) {
            return null;
        }

        if (Str::startsWith($value, ['http://', 'https://', 'data:', 'blob:'])) {
            return $value;
        }

        return asset(ltrim($value, '/'));
    }

    public function getIsLowStockAttribute(): bool
    {
        return (float) $this->stock <= (float) $this->min_stock;
    }
}
