<?php

namespace App\Models;

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

class ProductStock extends Model
{
    protected $fillable = [
        'organization_id',
        'product_id',
        'branch_id',
        'quantity',
    ];

    protected $casts = [
        'quantity' => 'integer',
    ];

    // ── Relationships ──────────────────────────────────────────────────────────

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

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

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

    // ── Helpers ────────────────────────────────────────────────────────────────

    /**
     * Safely increment stock, returning the updated model.
     */
    public static function addStock(int $productId, int $branchId, int $orgId, int $qty): self
    {
        $stock = self::firstOrCreate(
            ['product_id' => $productId, 'branch_id' => $branchId],
            ['organization_id' => $orgId, 'quantity' => 0]
        );
        $stock->increment('quantity', $qty);
        return $stock->fresh();
    }

    /**
     * Safely decrement stock within a lock context.
     * Caller must be inside a DB::transaction with lockForUpdate already acquired.
     */
    public static function deductStock(int $productId, int $branchId, int $qty, string $productName): self
    {
        $stock = self::where('product_id', $productId)
            ->where('branch_id', $branchId)
            ->lockForUpdate()
            ->first();

        if (!$stock || $stock->quantity < $qty) {
            $available = $stock?->quantity ?? 0;
            throw new \Exception(
                "Insufficient stock for '{$productName}' at this branch. Available: {$available}, Required: {$qty}"
            );
        }

        $stock->decrement('quantity', $qty);
        return $stock->fresh();
    }
}
