<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use App\Http\Helpers\ResponseBuilder;
use App\Modules\Shared\Infraestructure\Requester;

class Authenticate_ProviderReview
{
    protected $auth;

    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next, $guard = null)
    {
        $noDocumentInput = 'Provider_NoDocument';
        if ($request->input($noDocumentInput) == '') {
            return ResponseBuilder::Response([
                'Response_Status' => 401,
                'Response_Code' => 401,
                'Response_Domain' => 'global',
                'Response_Message' => 'Missing request authorization for method parameter',
                'Response_Data' => null,
                'Response_Error_Message' => 'Unauthorized',
                'Response_Error_Reason' => 'Missing request authorization for method parameter',
            ]);
        } else {
            $response = Requester::requestSelect(
                'CALL sp_provider_find_by_document_only(?,@sts,@cod,@msg)',
                [$request->input($noDocumentInput)]
            );
            if ($response['Response_Status'] == 200) {
                $request->provider = $response['Response_Data'][0];
                return $next($request);
            } else {
                $oResponse["Response_Status"]           = $response[0]->Response_Status;
                $oResponse["Response_Code"]             = $response[0]->Response_Code;
                $oResponse["Response_Domain"]           = "global";
                $oResponse["Response_Message"]          = $response[0]->Response_Message;
                $oResponse["Response_Data"]             = null;
                $oResponse["Response_Error_Message"]    = $response[0]->Response_Message;
                $oResponse["Response_Error_Reason"]     = $response[0]->Response_Reason;

                return ResponseBuilder::Response($oResponse);
            }
        }
    }
}
