<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Core\Auth;
use App\Core\MiddlewareInterface;
use App\Core\Request;
use App\Core\Response;
use App\Core\Tenant;

/**
 * GuestMiddleware
 *
 * The inverse of AuthMiddleware — attached to the login route so an
 * already-authenticated user is bounced straight to the dashboard
 * instead of seeing the login form again. Also requires a valid
 * tenant, same as AuthMiddleware: a login form only makes sense on an
 * actual company's subdomain.
 */
final class GuestMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, callable $next): Response
    {
        if (!Tenant::check()) {
            return Response::redirect(rtrim((string) config('app.marketing_url', config('app.url')), '/'));
        }

        if (Auth::check()) {
            return Response::redirect(base_url('dashboard'));
        }

        return $next($request);
    }
}
