<?php

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

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Inventory\StockTransactionRequest;
use App\Http\Requests\Api\V1\Inventory\StockAdjustmentRequest;
use App\Services\InventoryService;
use App\Services\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class InventoryController extends Controller
{
    public function __construct(
        protected InventoryService $inventoryService,
        protected ResponseService $responseService
    ) {}

    // Stock Ledger Endpoints
    public function stock(int $branchId): JsonResponse
    {
        $stock = $this->inventoryService->getStockForBranch($branchId);
        return $this->responseService->success($stock, 'Stock retrieved successfully');
    }

    public function stockForIngredient(int $branchId, int $ingredientId): JsonResponse
    {
        $stock = $this->inventoryService->getStockForIngredient($branchId, $ingredientId);

        if (!$stock) {
            return $this->responseService->error('Stock record not found', 404);
        }

        return $this->responseService->success($stock, 'Stock retrieved successfully');
    }

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

    public function outOfStock(int $branchId): JsonResponse
    {
        $stock = $this->inventoryService->getOutOfStock($branchId);
        return $this->responseService->success($stock, 'Out of stock items retrieved successfully');
    }

    // Stock Transaction Endpoints
    public function addStock(StockTransactionRequest $request, int $branchId): JsonResponse
    {
        $transaction = $this->inventoryService->addStock(
            $branchId,
            $request->ingredient_id,
            $request->quantity,
            $request->unit_cost,
            auth()->id(),
            $request->notes
        );

        return $this->responseService->success($transaction, 'Stock added successfully', 201);
    }

    public function deductStock(StockTransactionRequest $request, int $branchId): JsonResponse
    {
        $transaction = $this->inventoryService->deductStock(
            $branchId,
            $request->ingredient_id,
            $request->quantity,
            auth()->id(),
            $request->notes
        );

        return $this->responseService->success($transaction, 'Stock deducted successfully', 201);
    }

    public function adjustStock(StockAdjustmentRequest $request, int $branchId): JsonResponse
    {
        $transaction = match ($request->type) {
            'in' => $this->inventoryService->addStock(
                $branchId,
                $request->ingredient_id,
                $request->quantity,
                $request->unit_cost,
                auth()->id(),
                $request->notes
            ),
            'out' => $this->inventoryService->deductStock(
                $branchId,
                $request->ingredient_id,
                $request->quantity,
                auth()->id(),
                $request->notes
            ),
            'waste' => $this->inventoryService->recordWaste(
                $branchId,
                $request->ingredient_id,
                $request->quantity,
                auth()->id(),
                $request->notes
            ),
            'adjustment' => $this->inventoryService->adjustStock(
                $branchId,
                $request->ingredient_id,
                $request->quantity,
                auth()->id(),
                $request->notes
            ),
        };

        $messages = [
            'in' => 'Stock added successfully',
            'out' => 'Stock deducted successfully',
            'waste' => 'Waste recorded successfully',
            'adjustment' => 'Stock adjusted successfully',
        ];

        return $this->responseService->success($transaction, $messages[$request->type]);
    }

    public function recordWaste(StockTransactionRequest $request, int $branchId): JsonResponse
    {
        $transaction = $this->inventoryService->recordWaste(
            $branchId,
            $request->ingredient_id,
            $request->quantity,
            auth()->id(),
            $request->notes
        );

        return $this->responseService->success($transaction, 'Waste recorded successfully', 201);
    }

    // Transaction History
    public function transactions(Request $request, int $branchId): JsonResponse
    {
        $limit = $request->get('limit', 100);
        $transactions = $this->inventoryService->getTransactions($branchId, $limit);
        return $this->responseService->success($transactions, 'Transactions retrieved successfully');
    }

    public function transactionsForIngredient(Request $request, int $branchId, int $ingredientId): JsonResponse
    {
        $limit = $request->get('limit', 50);
        $transactions = $this->inventoryService->getTransactionsForIngredient($branchId, $ingredientId, $limit);
        return $this->responseService->success($transactions, 'Transactions retrieved successfully');
    }

    public function transactionsByDateRange(Request $request, int $branchId): JsonResponse
    {
        $request->validate([
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
        ]);

        $transactions = $this->inventoryService->getTransactionsByDateRange(
            $branchId,
            $request->start_date,
            $request->end_date
        );

        return $this->responseService->success($transactions, 'Transactions retrieved successfully');
    }

    // Stock Alerts
    public function alerts(Request $request, int $branchId): JsonResponse
    {
        $unresolvedOnly = $request->boolean('unresolved_only', true);
        $alerts = $this->inventoryService->getAlerts($branchId, $unresolvedOnly);
        return $this->responseService->success($alerts, 'Alerts retrieved successfully');
    }

    public function resolveAlert(int $branchId, int $alertId): JsonResponse
    {
        $alert = $this->inventoryService->resolveAlert($alertId);

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

        return $this->responseService->success($alert, 'Alert resolved successfully');
    }
}
