<?php

namespace App\Models;

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

class ProductVariation extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id',
        'size',
        'color',
        'color_hex',
        'sku',
        'price_adjustment',
        'stock',
    ];

    protected $casts = [
        'price_adjustment' => 'decimal:2',
        'stock' => 'integer',
    ];

    protected $appends = [];

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

    public function stock()
    {
        return $this->hasMany(Stock::class, 'variant_id');
    }

    // Accessors
    public function getFinalPriceAttribute()
    {
        $basePrice = $this->product ? $this->product->price : 0;
        return $basePrice + $this->price_adjustment;
    }

    public function getStockStatusAttribute()
    {
        $totalStock = $this->stock->sum('quantity');
        
        if ($totalStock <= 0) {
            return 'out_of_stock';
        }
        
        // Verificar se está baixo em alguma loja
        $hasLowStock = $this->stock->contains(function ($stock) {
            return $stock->is_low_stock;
        });
        
        if ($hasLowStock) {
            return 'low_stock';
        }
        
        return 'in_stock';
    }

    // Métodos auxiliares
    public function getTotalStock()
    {
        return $this->stock->sum('quantity');
    }

    public function getAvailableStock()
    {
        return $this->stock->sum('available_quantity');
    }

    public function hasStock()
    {
        return $this->getTotalStock() > 0;
    }

    public function isAvailable()
    {
        return $this->getAvailableStock() > 0;
    }
}