<?php

namespace App\Models\Tenant;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Part extends Model
{
    use BelongsToTenant, SoftDeletes;

    public const CATEGORIES = [
        'Ulei', 'Filtre', 'Frâne', 'Suspensie', 'Lichide',
        'Distribuție', 'Anvelope', 'Electrică', 'Caroserie', 'Altele',
    ];

    protected $fillable = [
        'company_id', 'name', 'article', 'brand', 'category',
        'qty', 'unit', 'min_qty',
        'buy_price', 'sell_price',
        'location', 'barcode', 'preferred_supplier_id',
        'is_active', 'notes',
    ];

    protected $casts = [
        'qty' => 'decimal:2',
        'min_qty' => 'decimal:2',
        'buy_price' => 'decimal:2',
        'sell_price' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    public function preferredSupplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class, 'preferred_supplier_id');
    }

    public function isLow(): bool
    {
        return (float) $this->qty <= (float) $this->min_qty;
    }

    public function isOut(): bool
    {
        return (float) $this->qty <= 0;
    }

    public function adjustStock(float $delta, ?string $reason = null): void
    {
        $this->qty = max(0, (float) $this->qty + $delta);
        $this->save();
    }
}
