<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $clientId = $request->get('apiKey');
        $clientSecret = $request->get('apiSecret');
        $accountId = $request->get('apiAccount');
        $response = \Illuminate\Support\Facades\Http::asForm()
            ->withHeaders([
                'Authorization' => ['Basic '.base64_encode("$clientId:$clientSecret")]
            ])->post('https://zoom.us/oauth/token', [
                'grant_type' => 'account_credentials',
                'account_id' => $accountId,
            ]);

        try {
            $accessToken = $response->json()['access_token'];

        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 422);
        }


        return $next($request);
    }
}
