<?php

namespace App\Models;

/**
 * Dual-write safety: skip movement-based stock recalc when location inventory is source of truth.
 */
trait ProductStockRecalcConcern
{
    public function recalculateStock(): int
    {
        // When location inventory is source of truth, do not stomp from legacy movements.
        if ($this->shouldSkipMovementRecalc()) {
            if ($this->product_type === 'variant' && is_null($this->parent_id)) {
                $calculatedStock = (int) $this->variants()->where('is_active', true)->sum('current_stock');
            } else {
                $calculatedStock = (int) InventoryBalance::query()
                    ->where('product_id', $this->id)
                    ->sum('on_hand');
            }
            $this->current_stock = $calculatedStock;
            $this->save();

            return $calculatedStock;
        }

        if ($this->product_type === 'variant' && is_null($this->parent_id)) {
            $calculatedStock = $this->variants()
                ->where('is_active', true)
                ->sum('current_stock');
        } elseif ($this->isVariant()) {
            $calculatedStock = $this->variantStockMovements()->sum('quantity');
        } else {
            $calculatedStock = $this->StockMovements()->sum('quantity');
        }
        $this->current_stock = $calculatedStock;
        $this->save();

        return $calculatedStock;
    }

    /**
     * Skip movement-based recalc when location inventory is on or legacy movements deprecated.
     */
    protected function shouldSkipMovementRecalc(): bool
    {
        try {
            if (app(\App\Services\LocationInventoryService::class)->useLocationInventory()) {
                return true;
            }
        } catch (\Throwable $e) {
        }
        try {
            $flag = Setting::get('inventory_legacy_movements_deprecated');
            if ($flag !== null && $flag !== '' && filter_var($flag, FILTER_VALIDATE_BOOLEAN)) {
                return true;
            }
        } catch (\Throwable $e) {
        }

        return false;
    }

    public function updateCurrentStock(): int
    {
        return $this->recalculateStock();
    }
}
