<?php

namespace App\Models;

use Deligoez\LaravelModelHashId\Traits\HasHashId;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Stock extends Model
{
    use HasFactory, SoftDeletes, HasHashId;

    protected $table = 'stock';

    protected $guarded = [];
    protected $appends = ['hash_id'];

    protected $casts = [
        'quantite' => 'integer',
        'seuil_alerte' => 'integer',
    ];

    public function magasin(): BelongsTo
    {
        return $this->belongsTo(Magasin::class);
    }

    public function produit(): BelongsTo
    {
        return $this->belongsTo(Produit::class);
    }

    public function isEnAlerte(): bool
    {
        return $this->quantite <= $this->seuil_alerte && $this->seuil_alerte > 0;
    }

    public function getStatutAttribute(): string
    {
        if ($this->seuil_alerte <= 0) {
            return 'ok';
        }
        if ($this->quantite <= 0) {
            return 'critique';
        }
        if ($this->quantite <= $this->seuil_alerte) {
            return $this->quantite <= $this->seuil_alerte / 2 ? 'critique' : 'alerte';
        }
        return 'ok';
    }
}