<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Illuminate\Support\Facades\Log;

class MattermostToken
{
    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure  $next
     * @return mixed
     *
     * @throws UnauthorizedHttpException
     */
    public function handle(Request $request, Closure $next)
    {
        if (!$request->token) {
            throw new UnauthorizedHttpException('Bearer', 'No token sent!');
        }

        $mattermostEnvTokens = config('mattermost');
        $urlParamKey = $request->path();

        Log::info('MattermostToken middleware', [
            'path' => $urlParamKey,
            'token' => $request->token,
            'config' => $mattermostEnvTokens,
        ]);

        if (!isset($mattermostEnvTokens[$urlParamKey])) {
            return $this->sendEnhancedResponse(
                "Invalid endpoint!", 
                false, 
                "ephemeral"
            );
        }

        if ($request->token !== $mattermostEnvTokens[$urlParamKey]) {
            return $this->sendEnhancedResponse(
                "Invalid token!", 
                false, 
                "ephemeral"
            );
        }

        return $next($request);
    }

    /**
     * Send an enhanced JSON response.
     *
     * @param string $message
     * @param bool $successBool
     * @param string $responseType
     * @return JsonResponse
     */
    private function sendEnhancedResponse(
        string $message,
        bool $successBool,
        string $responseType
    ): JsonResponse {
        return response()->json([
            'success'       => $successBool,
            'response_type' => $responseType,
            'username'      => 'Seraph',
            'text'         => $message
        ], $successBool ? 200 : 400);
    }
}

