<?php

namespace App\Repositories\Eloquent;

use App\Models\StockLedger;
use Illuminate\Database\Eloquent\Model;

class StockLedgerRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new StockLedger();
    }

    public function getForBranch(int $branchId)
    {
        return $this->model->forBranch($branchId)
            ->with('ingredient')
            ->get();
    }

    public function findByBranchAndIngredient(int $branchId, int $ingredientId): ?StockLedger
    {
        return $this->model->where('branch_id', $branchId)
            ->where('ingredient_id', $ingredientId)
            ->first();
    }

    public function getOrCreate(int $branchId, int $ingredientId): StockLedger
    {
        return $this->model->firstOrCreate(
            ['branch_id' => $branchId, 'ingredient_id' => $ingredientId],
            ['quantity' => 0, 'reserved_quantity' => 0, 'average_cost' => 0]
        );
    }

    public function getLowStockForBranch(int $branchId)
    {
        return $this->model->forBranch($branchId)
            ->with('ingredient')
            ->get()
            ->filter(fn ($ledger) => $ledger->isLowStock());
    }

    public function getOutOfStockForBranch(int $branchId)
    {
        return $this->model->forBranch($branchId)
            ->with('ingredient')
            ->get()
            ->filter(fn ($ledger) => $ledger->isOutOfStock());
    }

    public function updateQuantity(int $id, float $quantity, ?float $averageCost = null): StockLedger
    {
        $ledger = $this->find($id);
        $data = ['quantity' => $quantity];

        if ($averageCost !== null) {
            $data['average_cost'] = $averageCost;
        }

        if ($quantity > $ledger->quantity) {
            $data['last_restocked_at'] = now();
        }

        return $this->update($id, $data);
    }
}
