<?php

namespace App\Models;

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

class Stock extends Model
{
    use HasFactory;

    protected $table = 'stock';

    protected $fillable = [
        'product_id',
        'variant_id',
        'store_id',
        'quantity',
        'reserved_quantity',
        'min_stock_level',
        'max_stock_level',
        'last_restocked_at',
        'last_sold_at',
    ];

    protected $casts = [
        'quantity' => 'integer',
        'reserved_quantity' => 'integer',
        'min_stock_level' => 'integer',
        'max_stock_level' => 'integer',
        'last_restocked_at' => 'datetime',
        'last_sold_at' => 'datetime',
    ];

    protected $appends = ['available_quantity', 'is_low_stock', 'stock_status'];

    // Relationships
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function variation()
    {
        return $this->belongsTo(ProductVariation::class, 'variant_id');
    }

    public function store()
    {
        return $this->belongsTo(Store::class);
    }

    // Accessors
    public function getAvailableQuantityAttribute()
    {
        return max(0, $this->quantity - $this->reserved_quantity);
    }

    public function getIsLowStockAttribute()
    {
        return $this->available_quantity <= $this->min_stock_level;
    }

    public function getStockStatusAttribute()
    {
        if ($this->available_quantity <= 0) {
            return 'out_of_stock';
        }
        if ($this->is_low_stock) {
            return 'low_stock';
        }
        return 'in_stock';
    }

    // Scopes
    public function scopeLowStock($query)
    {
        return $query->whereRaw('(quantity - reserved_quantity) <= min_stock_level');
    }

    public function scopeOutOfStock($query)
    {
        return $query->whereRaw('(quantity - reserved_quantity) <= 0');
    }

    /**
     * Scope para incluir variações
     */
    public function scopeWithVariants($query)
    {
        return $query->with(['variation', 'product']);
    }

    /**
     * Scope para filtrar por variação específica
     */
    public function scopeForVariant($query, $variantId)
    {
        return $query->where('variant_id', $variantId);
    }

    /**
     * Scope para filtrar apenas itens com variações
     */
    public function scopeOnlyVariants($query)
    {
        return $query->whereNotNull('variant_id');
    }

    /**
     * Scope para filtrar apenas itens sem variações (produtos base)
     */
    public function scopeOnlyBaseProducts($query)
    {
        return $query->whereNull('variant_id');
    }
}