<?php

namespace App\Modules\Stock;

use Exception;

class StockTransactionObserver
{
    public function creating($model)
    {
        $this->updateStockQuantity($model, 'create');
    }

    public function updating($model)
    {
        $this->updateStockQuantity($model, 'update');
    }

    public function deleting($model)
    {
        $this->updateStockQuantity($model, 'delete');
    }

    /**
     * ------------------------------------------------
     * PROTECTED FUNCTIONS BELOW
     * ------------------------------------------------.
     */

    /**
     *	Update the stock quantity.
     *
     * @return void
     */
    protected function updateStockQuantity($model, $action)
    {
        $stock = Stock::withTrashed()->findOrFail($model->stock_id);

        if ($stock->unlimited) {
            return;
        }

        switch ($action) {
            case 'create':
                $stock->quantity = $stock->quantity + $model->quantity;
                break;

            case 'update':
                $stock->quantity -= $model->quantity -  $model->getOriginal('quantity');
                break;

            case 'delete':
                $stock->quantity = $stock->quantity -  $model->quantity;
                break;
        }

        // Skip validation when just updating quantity to avoid model_number uniqueness issues
        $stock->timestamps = false; // Don't update timestamps for quantity changes
        if (! $stock->saveQuietly()) {
            throw new Exception("Failed to update stock quantity for stock ID: {$stock->id}", 1);
        }
    }
}
