<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Interfaces\MemberRepositoryInterface;
use App\Services\Data\SettingsService;

use function _\find;

class ValidateAPIKey
{
    protected $member;
    protected $settings;

    public function __construct(
        MemberRepositoryInterface $memberRepo,
        SettingsService $settingsService,
    ) {
        $this->member   = $memberRepo;
        $this->settings = $settingsService;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = [];
        //checks to see if request is secure
        if (isHttps()) {
            $key   = $request->header('fipamo-api-key');
            $folks = $this->member->getAll();
            //looks to see if API key exists
            if (find($folks, ['key' => $key])) {
                //final check to see if API requests are being accepted
                $global = $this->settings->getGlobal();
                if (isset($global['externalAPI']) && $global['externalAPI'] == "true") {
                    return $next($request);
                } else {
                    $response = [
                        'message' => "API Auth Fail: Not Accepting Requests",
                        'type'    => 'postError',
                    ];
                    return response()->json($response)->header('Content-Type', 'application/json');
                }
            } else {
                $response = [
                    'message' => "API Auth Fail: API Key Invalid",
                    'type'    => 'postError',
                ];
                return response()->json($response)->header('Content-Type', 'application/json');
            }
        } else {
            $response = [
                'message' => "API Auth Fail: Request must be secure (HTTPS)",
                'type'    => 'postError',
            ];
            return response()->json($response)->header('Content-Type', 'application/json');
        }
    }
}