<?php

namespace App\Http\Middleware;

use App\Services\BasketService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\Response;

class BasketMiddleware
{
    protected BasketService $basketService;

    public function __construct(BasketService $basketService)
    {
        $this->basketService = $basketService;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Session ID kontrolü
        if (! Session::has('basket_session_id')) {
            Session::put('basket_session_id', (string) \Illuminate\Support\Str::uuid());
        }

        $sessionId = Session::get('basket_session_id');
        $ipAddress = $request->ip();
        $clientId = auth()->check() ? auth()->id() : null;

        // Sepet oluştur veya mevcut sepeti al
        $basket = $this->basketService->getOrCreateBasket($sessionId, $ipAddress, $clientId);

        // Request'e sepet bilgisini ekle
        $request->attributes->set('basket', $basket);
        $request->attributes->set('basket_session_id', $sessionId);

        // View'lara sepet bilgisini aktar
        view()->share('basket', $basket);
        view()->share('basket_session_id', $sessionId);

        return $next($request);
    }
}
