<?php

namespace App\Http\Middleware;

use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Models\User;

class DecryptTokenMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        // Retrieve the JWT token from the Authorization header
        $token = $request->header('Authorization');

        if (!$token) {
            return response()->json(['error' => 'Authorization token not provided']);
        }

        // Ensure the token follows the "Bearer {token}" format
        if (strpos($token, 'Bearer ') === 0) {
            $token = str_replace('Bearer ', '', $token); // Remove the "Bearer " prefix
        } else {
            return response()->json(['error' => 'Invalid token format']);
        }

        try {
            // Decode the JWT token
            $jwtSecret = env('JWT_SECRET'); // Retrieve the secret key from the .env file
            $decoded = JWT::decode($token, $jwtSecret, ['HS256']); // Decode using HS256

            // Assuming the decoded token contains the user ID
            $userId = $decoded->sub; // Adjust according to your JWT payload structure (sub is standard for user ID)

            // Fetch the user from the database
            $user = User::find($userId);

            if (!$user) {
                return response()->json(['error' => 'User not found']);
            }

            // Attach the user to the request for further use
            $request->attributes->set('user', $user);

        } catch (ExpiredException $e) {
            // Handle expired token case
            return response()->json(['error' => 'Token has expired']);
        } catch (SignatureInvalidException $e) {
            // Handle invalid signature case
            return response()->json(['error' => 'Invalid token signature']);
        } catch (\Exception $e) {
            // Handle any other token decoding issues
            Log::error('Token decoding error: ' . $e->getMessage());
            return response()->json(['error' => 'Invalid token']);
        }

        // Continue processing the request if the token is valid
        return $next($request);
    }
}
