<?php

namespace Lucent\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Lucent\Account\AccountService;
use Lucent\Account\AuthService;
use Lucent\Channel\ChannelService;
use Lucent\ViewModel\ViewModel;

readonly class AuthMiddleware
{
    public function __construct(
        private AuthService $authService,
        private AccountService $accountService,
        private ChannelService $channelService,
        private ViewModel $viewModel
    )
    {
    }

    public function handle(Request $request, Closure $next)
    {
        if (!$this->authService->isLoggedIn()) {
            return redirect($this->channelService->channel->lucentUrl . "/login");
        }
        $this->authService->refreshSession();
        View::share("channel",$this->channelService->channel);
        View::share("user",session("user"));
        View::share("schemas",$this->channelService->channel->schemas->whereIn("name",$this->accountService->currentReadableSchemas())->values());
        View::share("viewModel",$this->viewModel);

        return $next($request);
    }
}
