<?php

namespace App\Models;

use App\Models\Concerns\BelongsToUser;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Mouvement extends Model
{
    use BelongsToUser, HasFactory, SoftDeletes;

    protected $fillable = ['type', 'magasin_id', 'produit_id', 'quantite', 'reference', 'user_id'];

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

    public const TYPE_ENTREE = 'entree';
    public const TYPE_SORTIE = 'sortie';
    public const TYPE_TRANSFERT = 'transfert';
    public const TYPE_STOCK_INITIAL = 'stock_initial';
    public const TYPE_STOCK_FINAL = 'stock_final';

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

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

    public function isEntree(): bool
    {
        return $this->quantite > 0 || $this->type === self::TYPE_ENTREE;
    }

    public function isSortie(): bool
    {
        return $this->quantite < 0 || $this->type === self::TYPE_SORTIE;
    }

    //Générer la référence du mouvement lors de la création
    protected static function booted()
    {
        static::creating(function ($mouvement) {
            if (empty($mouvement->reference)) {
                $mouvement->reference = 'MOV-00' . strtoupper(Str::random(2));
            }
        });
    }
}
