<?php

namespace App\Repositories\Eloquent;

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

class StockTransactionRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new StockTransaction();
    }

    public function getForBranch(int $branchId, int $limit = 100)
    {
        return $this->model->forBranch($branchId)
            ->with(['ingredient', 'user'])
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }

    public function getForIngredient(int $branchId, int $ingredientId, int $limit = 50)
    {
        return $this->model->forBranch($branchId)
            ->forIngredient($ingredientId)
            ->with(['user'])
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }

    public function getByType(int $branchId, string $type, int $limit = 100)
    {
        return $this->model->forBranch($branchId)
            ->byType($type)
            ->with(['ingredient', 'user'])
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }

    public function getByDateRange(int $branchId, $startDate, $endDate)
    {
        return $this->model->forBranch($branchId)
            ->dateRange($startDate, $endDate)
            ->with(['ingredient', 'user'])
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function getSummaryByIngredient(int $branchId, $startDate, $endDate)
    {
        return $this->model->forBranch($branchId)
            ->dateRange($startDate, $endDate)
            ->selectRaw('ingredient_id, type, SUM(quantity) as total_quantity, SUM(ABS(quantity) * COALESCE(unit_cost, 0)) as total_value')
            ->groupBy('ingredient_id', 'type')
            ->with('ingredient')
            ->get();
    }
}
