<?php

namespace App\Http\Middleware;

use App\Models\Contract;
use App\Services\Api\V1\ResponseService;
use App\Services\Log;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ContractKeyVerification {
	/**
	 * Handle an incoming request.
	 *
	 * @param Request $request
	 * @param Closure(Request): (Response) $next
	 *
	 * @return Response
	 */
	public function handle( Request $request, Closure $next ): Response {
		$contractKey = Contract::where( 'contract_key', $request->contract_key )->first();

		if ( ! $contractKey ) {
			Log::add( '211', $request->contract_key ?? '-', request()->ip(), array_merge( [ 'endpoint' => $request->route()->getName() ], $request->all() ) );

			return ResponseService::respond( [
				'response' => [
					'code'    => 1000,
					'message' => __( 'Contract not found' )
				]
			], 401 );

		}else {
			$contractKey = $contractKey->toArray();

			if ( $contractKey['status'] == 'inactive' ) {
				Log::add( '212', $request->contract_key ?? '-', request()->ip(), array_merge( [ 'endpoint' => $request->route()->getName() ], $request->all() ) );

				return ResponseService::respond( [
					'response' => [
						'code'    => 1001,
						'message' => __( 'Inactive contract' )
					]
				], 401 );
			} else {
				$capability = explode( '.', $request->route()->getName() );

				if ( ! $contractKey[ 'can_' . str_replace( '-', '_', $capability[0] ) ] ) {
					Log::add( '213', $request->contract_key, request()->ip(), array_merge( [ 'endpoint' => $request->route()->getName() ], $request->all() ) );

					return ResponseService::respond( [
						'response' => [
							'code'    => 1102,
							'message' => __( "The contract associated with the used contract key doesn't have the required permission to access this endpoint" )
						]
					], 401 );
				}
			}
		}

		return $next( $request );
	}
}
