<?php

namespace App\Models\Tenant;

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

class StockMovement extends Model
{
    use HasFactory;
    
    protected $connection = 'tenant';
    protected $guarded = [];
    
    protected $casts = [
        'quantity' => 'decimal:2',
        'created_at' => 'datetime',
    ];

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

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

    public function user()
    {
        return $this->belongsTo(\App\Models\User::class);
    }

    /**
     * Record a stock movement
     */
    public static function record($variantId, $quantity, $movementType, $referenceType = null, $referenceId = null, $notes = null)
    {
        return static::create([
            'variant_id' => $variantId,
            'quantity' => $quantity,
            'movement_type' => $movementType, // sale, purchase, adjustment, return
            'reference_type' => $referenceType, // sale, purchase, manual
            'reference_id' => $referenceId,
            'user_id' => auth()->id(),
            'notes' => $notes,
        ]);
    }

    /**
     * Get movement type label
     */
    public function getMovementTypeLabelAttribute()
    {
        return match($this->movement_type) {
            'sale' => 'Sale',
            'purchase' => 'Purchase',
            'adjustment' => 'Stock Adjustment',
            'return' => 'Return',
            'damage' => 'Damage/Loss',
            default => ucfirst($this->movement_type),
        };
    }

    /**
     * Get quantity with sign
     */
    public function getQuantityWithSignAttribute()
    {
        $sign = in_array($this->movement_type, ['sale', 'damage']) ? '-' : '+';
        return $sign . abs($this->quantity);
    }
}
