<?php

namespace App\Http\Middleware;

use App\Services\Api\V1\ResponseService;
use App\Services\Log;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class ApiAccessRestrictions {
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response) $next
     *
     * @return Response
     */
    public function handle( Request $request, Closure $next ): Response {
        if ( in_array( $request->ip(), explode( ',', getOption( 'api', 'blockedIPs' ) ) ) ) {

            Log::add( '205', $request->api_key ?? '-', request()->ip(), array_merge( [ 'endpoint' => $request->route()->getName() ], $request->all() ) );

            return ResponseService::sign( [
                'response' => [
                    'code'    => 150,
                    'message' => __( 'Access denied' )
                ]
            ], 403 );
        }

        if ( isset( $request->identifier ) && in_array( $request->identifier, explode( ',', getOption( 'api', 'blockedIdentifiers' ) ) ) ) {

            Log::add( '206', $request->api_key ?? '-', request()->ip(), array_merge( [ 'endpoint' => $request->route()->getName() ], $request->all() ) );

            return ResponseService::sign( [
                'response' => [
                    'code'    => 150,
                    'message' => __( 'Access denied' )
                ]
            ], 403 );
        }

        return $next( $request );
    }
}
