<?php
namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Http\Requests\Client\StoreBesoinRequest;
use App\Http\Resources\Client\BesoinResource;
use App\Http\Resources\Client\BesoinDetailResource;
use App\Services\BesoinService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class BesoinController extends Controller
{
    public function __construct(private readonly BesoinService $besoinService) {}

    public function index(Request $request): JsonResponse
    {
        $client = $request->user()->client()->firstOrFail();
        $statut = $request->query('statut');
        
        $besoins = $this->besoinService->listerBesoinsClient($client, $statut);

        return response()->json([
            'besoins' => BesoinResource::collection($besoins),
            'pagination' => [
                'current_page' => $besoins->currentPage(),
                'last_page' => $besoins->lastPage(),
                'per_page' => $besoins->perPage(),
                'total' => $besoins->total(),
            ],
        ]);
    }

    public function store(StoreBesoinRequest $request): JsonResponse
    {
        $user = $request->user()->load('client');
        $client = $user->client;
        if (!$client) {
            return response()->json(['message' => 'Client non trouvé'], 404);
        }
        
        $besoin = $this->besoinService->creerBesoin($client, $request->validated());

        return response()->json([
            'message' => 'Votre demande a bien été enregistrée.',
            'besoin' => new BesoinDetailResource($besoin),
        ], 201);
    }

    public function show(Request $request, string $reference): JsonResponse
    {
        $client = $request->user()->client()->firstOrFail();
        $besoin = $this->besoinService->getBesoinDuClient($client, $reference);

        return response()->json([
            'besoin' => new BesoinDetailResource($besoin),
        ]);
    }

    public function annuler(Request $request, string $reference): JsonResponse
    {
        $client = $request->user()->client()->firstOrFail();
        $besoin = $this->besoinService->annulerBesoin($client, $reference);

        return response()->json([
            'message' => 'Votre demande a été annulée.',
            'besoin' => new BesoinDetailResource($besoin),
        ]);
    }
}
