<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

use App\Models\CustomToken as CustomTokenModel;

class CustomToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $accessToken = '';

        if (!empty($request->hasHeader('Authorization'))) {
            $header = $request->header('Authorization');
            if (substr($header, 0, 7) === 'Bearer ') {
                $accessToken = trim(substr($header, 7));
                $CustomTokenModel = CustomTokenModel::where('token', $accessToken)->first();

                if ($CustomTokenModel) {
                    return $next($request);
                } else {
                    return response()->json([
                        "code" => 403,
                        "message" => "Unauthorized"
                    ], 403);
                }
            }
        } else {
            return response()->json([
                "code" => 403,
                "message" => "Unauthorized"
            ], 403);
        }
    }
}
