<?php

namespace App\Http\Middleware;

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

class CheckAPIAuthorization
{
    /**
     * 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)
    {
        // Retrieve the Authorization header
        $authorizationHeader = $request->header('Authorization');

        // You can add your logic here, for example, to check if the header is present
        if (!$authorizationHeader) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $apiRecord     = null;
        $allApiRecords = MetaMintAPI::all();

        foreach ($allApiRecords as $record) {
            if (\Hash::check($authorizationHeader, $record->api_salt)) {
                $apiRecord = $record;
                break;
            }
        }

        $request->attributes->set('Authorization', $authorizationHeader);

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