<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiHttpException;
use App\Facades\PatientService;
use Closure;
use Illuminate\Http\Request;

class CheckToken
{
    public function handle(Request $request, Closure $next)
    {
        $token = $request->bearerToken() ?? $request->header('X-Patient-Token');

        if (empty($token)) {
            throw new ApiHttpException(401, 'token_not_provided');
        }

        try {
            $patient = PatientService::checkPatientToken(['token' => $token]);

            if (empty($patient)) {
                throw new ApiHttpException(401, 'invalid_token');
            }

            $request->merge(['authenticated_patient' => $patient]);

        } catch (ApiHttpException $e) {
            throw new ApiHttpException(401, 'invalid_or_expired_token');
        }

        return $next($request);
    }
}
