<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Models\Consumable;
use App\Models\User;
use App\Models\InstallerConsumable;
use App\Models\StockLog;
use Illuminate\Support\Facades\DB;

class InstallerStockController extends Controller
{
    /**
     * Остатки монтажника + центральный склад + история
     */
    public function index(User $installer): JsonResponse
    {
        $consumables = Consumable::all();

        $personal = InstallerConsumable::where('installer_id', $installer->id)
            ->pluck('stock', 'consumable_id');

        $result = $consumables->map(function ($c) use ($personal) {
            return [
                'id' => $c->id,
                'name' => $c->name,
                'unit' => $c->unit,
                'central_stock' => $c->stock,
                'personal_stock' => $personal[$c->id] ?? 0,
            ];
        });

        $logs = StockLog::where('installer_id', $installer->id)
            ->with('consumable:id,name')
            ->orderByDesc('id')
            ->limit(50)
            ->get();

        return response()->json([
            'installer' => $installer,
            'stock' => $result,
            'logs' => $logs,
        ]);
    }

    /**
     * Выдача расходника монтажнику
     */
    public function refill(Request $request, User $installer): JsonResponse
    {
        $validated = $request->validate([
            'consumable_id' => 'required|exists:consumables,id',
            'quantity' => 'required|integer|min:1',
        ]);

        return DB::transaction(function () use ($validated, $installer) {
            $consumable = Consumable::find($validated['consumable_id']);

            if ($consumable->stock < $validated['quantity']) {
                return response()->json([
                    'message' => 'Недостаточно на центральном складе'
                ], 422);
            }

            // списание
            $consumable->decrement('stock', $validated['quantity']);

            // добавление монтажнику
            InstallerConsumable::updateOrCreate(
                [
                    'installer_id' => $installer->id,
                    'consumable_id' => $validated['consumable_id']
                ],
                [
                    'stock' => DB::raw('stock + ' . $validated['quantity'])
                ]
            );

            // лог
            StockLog::create([
                'consumable_id' => $validated['consumable_id'],
                'installer_id' => $installer->id,
                'type' => 'issue',
                'quantity' => $validated['quantity'],
            ]);

            return response()->json(['message' => 'Выдано успешно']);
        });
    }
}
