<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreInventoryBulkAdjustCsvRequest;
use App\Services\InventoryBulkAdjustCsvService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class InventoryBulkAdjustCsvController extends Controller
{
    public function store(
        StoreInventoryBulkAdjustCsvRequest $request,
        InventoryBulkAdjustCsvService $service
    ): JsonResponse {
        $userId = Auth::id();
        if ($userId === null) {
            return response()->json(['message' => 'No autenticado.'], JsonResponse::HTTP_UNAUTHORIZED);
        }

        try {
            $result = $service->apply($request->file('file'), $userId);
        } catch (\InvalidArgumentException $e) {
            return response()->json([
                'message' => $e->getMessage(),
                'errors' => ['file' => [$e->getMessage()]],
            ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
        }

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