<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ProductReturn;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class ProductReturnController extends Controller
{
    public function store(Request $request)
    {
        // 1. Validation des données
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity'   => 'required|integer|min:1',
            'site'     => 'required|string|max:255',
            'reason'     => 'required|string|max:255',
        ]);

        // 2. Utilisation d'une transaction pour garantir la cohérence
        return DB::transaction(function () use ($validated) {

            // On récupère le produit
            $product = Product::findOrFail($validated['product_id']);

            // 3. Création de l'enregistrement de retour
            $productReturn = ProductReturn::create([
                'product_id'  => $validated['product_id'],
                'quantity'    => $validated['quantity'],
                'site'      => $validated['site'],
                'reason'      => $validated['reason'],
                'returned_by' => Auth::user()->name ?? 'Utilisateur inconnu',
            ]);

            // 4. Augmentation du stock
            $product->increment('quantity', $validated['quantity']);

            return response()->json([
                'message' => 'Retour enregistré et stock mis à jour (+'.$validated['quantity'].')',
                'data' => $productReturn,
                'new_stock' => $product->quantity
            ], 201);
        });
    }

    // Pour l'historique des retours
    public function index()
    {
        return response()->json(ProductReturn::with('product')->orderBy('created_at', 'desc')->get());
    }
}
