<?php

namespace App\Http\Middleware;

use App\Models\OtpVerification;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserIDVerified
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        $telephone = $user?->{'telephone'} ?? $request->{'telephone'};

        /** @var OtpVerification $otpEntry */
        $otpEntry = OtpVerification::findByEmailOrTelephone(telephone: $telephone, email: null);

        if($otpEntry === null || ! $otpEntry->isValidated()) {
            return api_response(101, __('errors.telephone_not_verified'));
        }

        return $next($request);
    }
}
