<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;
use App\Exceptions\ModelNotFoundException;
use App\Models\Restaurante;

class InRestauranteMiddleware {
    public function handle($request, Closure $next) {
        $restaurante = Restaurante::findOrFail($request->route('restaurante_id'));
        $user = $request->user;

        if(!$user->isOnRestaurante($restaurante)) {
            Log::debug('El usuario intento acceder a un restaurante que no le pertenece', [
                'user' => $user->id,
                'restaurante' => $restaurante->id
            ]);
            throw new ModelNotFoundException('restaurante', $restaurante->id);
        } else {
            Log::debug('El usuario accedio a un restaurante que si le pertenece', [
                'user' => $user->id,
                'restaurante' => $restaurante->id
            ]);
        }

        return $next($request);
    }
}
