<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreInventoryMovementRequest;
use App\Models\InventoryMovement;
use App\Models\InventoryProduct;
use App\Services\InventoryMovementService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class InventoryMovementController extends Controller
{
    public function index(Request $request, InventoryProduct $inventory_product): JsonResponse
    {
        $this->authorize('viewAny', InventoryMovement::class);

        $perPage = min(100, max(5, (int) $request->get('per_page', 20)));

        $paginator = $inventory_product->movements()
            ->with(['user:id,name'])
            ->orderByDesc('created_at')
            ->paginate($perPage);

        return response()->json([
            'data' => $paginator,
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_OK);
    }

    public function store(
        StoreInventoryMovementRequest $request,
        InventoryProduct $inventory_product,
        InventoryMovementService $service
    ): JsonResponse {
        $this->authorize('create', InventoryMovement::class);

        $userId = Auth::id();
        if ($userId === null) {
            return response()->json(['message' => 'No autenticado.'], JsonResponse::HTTP_UNAUTHORIZED);
        }

        try {
            $movement = $service->record(
                $inventory_product,
                $request->validated('type'),
                (string) $request->validated('quantity'),
                $request->validated('reference'),
                $userId
            );
        } catch (\InvalidArgumentException $e) {
            return response()->json([
                'message' => $e->getMessage(),
                'errors' => ['quantity' => [$e->getMessage()]],
            ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
        }

        $inventory_product->refresh();

        return response()->json([
            'data' => [
                'movement' => $movement->load('user:id,name'),
                'product' => $inventory_product->load(['productType', 'brand', 'category', 'subcategory', 'supplier']),
            ],
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_CREATED);
    }
}
