<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Inventory extends Model
{
    protected $table = 'inventory';

    protected $fillable = [
        'product_id',
        'branch_id',
        'location_id',
        'quantity',
        'avg_cost',
    ];

    protected $casts = [
        'quantity' => 'integer',
        'avg_cost' => 'decimal:2',
    ];

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

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

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

    public function scopeLowStock($query)
    {
        return $query->whereHas('product', function ($q) {
            $q->whereColumn('inventory.quantity', '<=', 'products.min_stock_level');
        });
    }

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

    /**
     * Get the total value of inventory
     */
    public function getTotalValueAttribute(): float
    {
        return $this->quantity * $this->avg_cost;
    }

    /**
     * Update quantity and recalculate weighted average cost
     */
    public function addStock(int $quantity, float $unitCost): self
    {
        $totalCost = ($this->quantity * $this->avg_cost) + ($quantity * $unitCost);
        $totalQuantity = $this->quantity + $quantity;

        $this->avg_cost = $totalQuantity > 0 ? $totalCost / $totalQuantity : $unitCost;
        $this->quantity = $totalQuantity;
        $this->save();

        return $this;
    }

    /**
     * Reduce stock
     */
    public function reduceStock(int $quantity): self
    {
        $this->quantity = max(0, $this->quantity - $quantity);
        $this->save();

        return $this;
    }

    /**
     * Find or create inventory record
     */
    public static function findOrCreateForProduct(int $productId, int $branchId, ?int $locationId = null): self
    {
        return static::firstOrCreate(
            ['product_id' => $productId, 'branch_id' => $branchId, 'location_id' => $locationId],
            ['quantity' => 0, 'avg_cost' => 0]
        );
    }
}
