<?php

namespace App\Http\Controllers\Api\V1\Recipe;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Recipe\StoreIngredientRequest;
use App\Http\Requests\Api\V1\Recipe\UpdateIngredientRequest;
use App\Services\IngredientService;
use App\Services\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class IngredientController extends Controller
{
    public function __construct(
        protected IngredientService $ingredientService,
        protected ResponseService $responseService
    ) {}

    public function index(): JsonResponse
    {
        $ingredients = $this->ingredientService->getAll();
        return $this->responseService->success($ingredients, 'Ingredients retrieved successfully');
    }

    public function active(): JsonResponse
    {
        $ingredients = $this->ingredientService->getActive();
        return $this->responseService->success($ingredients, 'Active ingredients retrieved successfully');
    }

    public function search(Request $request): JsonResponse
    {
        $request->validate(['term' => 'required|string|min:2']);

        $ingredients = $this->ingredientService->search($request->term);
        return $this->responseService->success($ingredients, 'Ingredients search results');
    }

    public function lowStock(): JsonResponse
    {
        $ingredients = $this->ingredientService->getLowStock();
        return $this->responseService->success($ingredients, 'Low stock ingredients retrieved successfully');
    }

    public function store(StoreIngredientRequest $request): JsonResponse
    {
        $ingredient = $this->ingredientService->create($request->validated());
        return $this->responseService->success($ingredient, 'Ingredient created successfully', 201);
    }

    public function show(int $id): JsonResponse
    {
        $ingredient = $this->ingredientService->find($id);

        if (!$ingredient) {
            return $this->responseService->error('Ingredient not found', 404);
        }

        return $this->responseService->success($ingredient, 'Ingredient retrieved successfully');
    }

    public function update(UpdateIngredientRequest $request, int $id): JsonResponse
    {
        $ingredient = $this->ingredientService->find($id);

        if (!$ingredient) {
            return $this->responseService->error('Ingredient not found', 404);
        }

        $ingredient = $this->ingredientService->update($id, $request->validated());
        return $this->responseService->success($ingredient, 'Ingredient updated successfully');
    }

    public function destroy(int $id): JsonResponse
    {
        $ingredient = $this->ingredientService->find($id);

        if (!$ingredient) {
            return $this->responseService->error('Ingredient not found', 404);
        }

        $this->ingredientService->delete($id);
        return $this->responseService->success(null, 'Ingredient deleted successfully');
    }
}
