<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\InventoryMovements\StoreInventoryMovementRequest;
use App\Http\Requests\InventoryMovements\UpdateInventoryMovementRequest;
use App\Models\InventoryItem;
use App\Models\InventoryMovement;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class InventoryMovementController extends Controller
{
    private function mapRef(array $payload): array
    {
        if (array_key_exists('ref', $payload)) {
            $payload['ref_json'] = $payload['ref'];
            unset($payload['ref']);
        }

        return $payload;
    }

    public function index(): JsonResponse
    {
        $userId = Auth::id();

        $items = InventoryMovement::query()
            ->where('user_id', $userId)
            ->orderByDesc('date')
            ->orderByDesc('id')
            ->get();

        return $this->success($items, 'Inventory movements list');
    }

    public function store(StoreInventoryMovementRequest $request): JsonResponse
    {
        $userId = Auth::id();
        $validated = $this->mapRef($request->validated());

        $itemId = (int) ($validated['item_id'] ?? 0);
        $ownsItem = InventoryItem::query()->where('id', $itemId)->where('user_id', $userId)->exists();
        if (!$ownsItem) {
            return $this->error('Invalid item_id', 422);
        }

        $movement = InventoryMovement::create(array_merge($validated, ['user_id' => $userId]));

        return $this->success($movement, 'Inventory movement created', 201);
    }

    public function show(InventoryMovement $inventoryMovement): JsonResponse
    {
        $userId = Auth::id();
        if ((int) $inventoryMovement->user_id !== (int) $userId) {
            return $this->error('Not found', 404);
        }

        return $this->success($inventoryMovement, 'Inventory movement details');
    }

    public function update(UpdateInventoryMovementRequest $request, InventoryMovement $inventoryMovement): JsonResponse
    {
        $userId = Auth::id();
        if ((int) $inventoryMovement->user_id !== (int) $userId) {
            return $this->error('Not found', 404);
        }

        $validated = $this->mapRef($request->validated());

        if (array_key_exists('item_id', $validated)) {
            $itemId = (int) ($validated['item_id'] ?? 0);
            $ownsItem = InventoryItem::query()->where('id', $itemId)->where('user_id', $userId)->exists();
            if (!$ownsItem) {
                return $this->error('Invalid item_id', 422);
            }
        }

        $inventoryMovement->update($validated);

        return $this->success($inventoryMovement, 'Inventory movement updated');
    }

    public function destroy(InventoryMovement $inventoryMovement): JsonResponse
    {
        $userId = Auth::id();
        if ((int) $inventoryMovement->user_id !== (int) $userId) {
            return $this->error('Not found', 404);
        }

        $inventoryMovement->delete();

        return $this->success(null, 'Inventory movement deleted');
    }
}
