<?php
/**
 * Auth guards — protect pages and APIs.
 */

declare(strict_types=1);

class Auth
{
    /**
     * Page guard — redirect to login if not signed in.
     * Use at top of every protected page.
     */
    public static function requireLogin(string $redirectTo = '/login'): array
    {
        $user = Session::current();
        if (!$user) {
            $next = urlencode($_SERVER['REQUEST_URI'] ?? '/dashboard');
            redirect($redirectTo . '?next=' . $next);
        }
        return $user;
    }

    /**
     * Page guard — redirect to dashboard if already signed in.
     * Use on /login, /register, /forgot-password etc.
     */
    public static function requireGuest(string $redirectTo = '/dashboard'): void
    {
        if (Session::isLoggedIn()) {
            redirect($redirectTo);
        }
    }

    /**
     * API guard — return JSON 401 if not signed in.
     * Use at top of every protected API endpoint.
     */
    public static function apiRequireLogin(): array
    {
        $user = Session::current();
        if (!$user) {
            jsonError('Unauthorized. Please log in.', 401);
        }
        return $user;
    }

    /**
     * API guard — for endpoints that should only work when guest.
     */
    public static function apiRequireGuest(): void
    {
        if (Session::isLoggedIn()) {
            jsonError('Already logged in.', 400);
        }
    }
}
