<?php

namespace App\Http\Middleware;

use Closure;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\File;

class VerifyToken
{
    public function handle($request, Closure $next)
    {
        try {
            if (!empty($request->headers->get('Authorization'))) {
                $token = $request->headers->get('Authorization');
            }
            if (!empty($request->query('authorization'))) {
                $token = $request->query('authorization');
            }

            $token_replaced = str_replace(['/', '.'], '', $token);
            if (empty($token)) {
                return response()->json(['message' => 'token_not_found'], 401);
            }

            $fileName = 'app/public/' . $token_replaced . '.txt';

            $file = storage_path($fileName);

            if (!File::exists($file)) {
                $client = new Client();
                $url = env('URL_AUTH') . 'auth/check';
                $response = $client->request('POST', $url, [
                    'headers' => [
                        'Authorization' => "Bearer " . $token,
                    ],
                    'http_errors' => false,
                ]);

                if ($response->getStatusCode() !== 200) {
                    return response()->json(['message' => 'invalid_token'], 401);
                }
            }

            $fileContents = [
                'data' =>  $token,
                'created_at' => now(),
            ];

            $encodedContents = json_encode($fileContents);

            $file = storage_path($fileName);
            File::put($file, $encodedContents);

            return $next($request);
        } catch (RequestException $e) {
            if ($e->getResponse() && $e->getResponse()->getStatusCode() === 401) {
                return response()->json(['message' => 'unauthorized'], 401);
            }

            return response()->json(['message' => 'internal_error'], 500);
        }
    }
}
