<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CookieToBearer
{
    public function handle(Request $request, Closure $next)
    {
        // Ambil nilai header Authorization saat ini
        $authHeader = $request->header('Authorization');

        // Deteksi apakah header kosong, tidak ada, atau membawa string null
        $needsTokenInjection = empty($authHeader) || trim($authHeader) === 'Bearer' || $authHeader === 'Bearer null';

        if ($request->hasCookie('admin_token') && $needsTokenInjection) {
            // Ambil token dan decode (jaga-jaga jika karakter '|' berubah jadi '%7C')
            $token = urldecode($request->cookie('admin_token'));
            
            $request->headers->set('Authorization', 'Bearer ' . $token);
        }
        
        return $next($request);
    }
}