<?php

namespace App\Http\Middleware;

use App\Models\PersonalAccessTokens;
use Closure;
use Illuminate\Http\Request;

class TokenCheckerMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        //Method 1: Token pass via query parameter
        // Check if the api_key query parameter is present
        if (!$request->query('api-key')) {
            return response()->json(['message' => 'Invalid API key.'], 401);
        }

        // Check if the api_key is valid
        $apiKey = $request->query('api-key');
        $personalAccessToken = PersonalAccessTokens::where('token', $apiKey)->first();
        if($personalAccessToken){
            $request->merge(['apiKeyExist' => $personalAccessToken->token]);
        }

        if (!$personalAccessToken) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        return $next($request);

        //Method 2: Token pass via request header
        /*
        $authHeader = $request->header('Authorization');
        if (preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
            $token = $matches[1];
            // validate the token here

            $personalAccessToken = PersonalAccessToken::where('token', $token)->first();

            if (!$personalAccessToken) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }


            // if the token is valid, you can attach it to the request
            $request->attributes->add(['bearerToken' => $token]);
            return $next($request);
        }
        return response()->json(['error' => 'Unauthorized'], 401);
        */
    }
}
