<?php

namespace App\Repositories\Eloquent;

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

class StockAlertRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new StockAlert();
    }

    public function getForBranch(int $branchId, bool $unresolvedOnly = true)
    {
        $query = $this->model->forBranch($branchId)
            ->with('ingredient')
            ->orderBy('created_at', 'desc');

        if ($unresolvedOnly) {
            $query->unresolved();
        }

        return $query->get();
    }

    public function getByType(int $branchId, string $type)
    {
        return $this->model->forBranch($branchId)
            ->byType($type)
            ->unresolved()
            ->with('ingredient')
            ->get();
    }

    public function findUnresolvedForIngredient(int $branchId, int $ingredientId, string $alertType): ?StockAlert
    {
        return $this->model->where('branch_id', $branchId)
            ->where('ingredient_id', $ingredientId)
            ->where('alert_type', $alertType)
            ->unresolved()
            ->first();
    }

    public function createOrUpdateAlert(int $branchId, int $ingredientId, string $alertType, float $currentQty, float $thresholdQty): StockAlert
    {
        $existingAlert = $this->findUnresolvedForIngredient($branchId, $ingredientId, $alertType);

        if ($existingAlert) {
            return $this->update($existingAlert->id, [
                'current_quantity' => $currentQty,
                'threshold_quantity' => $thresholdQty,
            ]);
        }

        return $this->create([
            'branch_id' => $branchId,
            'ingredient_id' => $ingredientId,
            'alert_type' => $alertType,
            'current_quantity' => $currentQty,
            'threshold_quantity' => $thresholdQty,
        ]);
    }

    public function resolveAlertsForIngredient(int $branchId, int $ingredientId): int
    {
        return $this->model->where('branch_id', $branchId)
            ->where('ingredient_id', $ingredientId)
            ->unresolved()
            ->update([
                'is_resolved' => true,
                'resolved_at' => now(),
            ]);
    }
}
