<?php

namespace App\Models;

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

class ProductVariant extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id',
        'sku',
        'item_code',
        'price',
        'purchase_price',
        'wholesale_price',
        'mrp',
        'current_stock',
        'opening_stock',
        'barcode',
        'image_path',
        'hsn_code',
        'warranty_months',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'purchase_price' => 'decimal:2',
            'wholesale_price' => 'decimal:2',
            'mrp' => 'decimal:2',
            'current_stock' => 'integer',
            'opening_stock' => 'integer',
            'warranty_months' => 'integer',
            'is_active' => 'boolean',
        ];
    }

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

    public function attributeValues()
    {
        return $this->belongsToMany(AttributeValue::class, 'product_variant_attribute_values')
            ->withTimestamps();
    }

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

    public function cartItems()
    {
        return $this->hasMany(CartItem::class);
    }

    public function orderItems()
    {
        return $this->hasMany(OrderItem::class);
    }

    public function updateCurrentStock(): int
    {
        $calculatedStock = $this->stockMovements()->sum('quantity');
        $this->update(['current_stock' => $calculatedStock]);
        return $calculatedStock;
    }

    public function recalculateStock(): int
    {
        $calculatedStock = $this->stockMovements()->sum('quantity');
        $this->current_stock = $calculatedStock;
        $this->save();
        return $calculatedStock;
    }

    public function getVariationNameAttribute(): string
    {
        $attributeValues = $this->attributeValues;
        if ($attributeValues->isEmpty()) {
            return $this->sku;
        }
        
        return $attributeValues->map(function ($value) {
            return $value->attribute->name . ': ' . $value->value;
        })->implode(' - ');
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeInStock($query)
    {
        return $query->where('current_stock', '>', 0);
    }
}
