<?php

namespace App\Filters;

use App\Services\PersistentLoginService;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Public auth screens. Authenticated users (including persistent-login restore)
 * are sent to Dashboard or first-login onboarding.
 */
class GuestFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();

        if (! $session->get('user_id')) {
            (new PersistentLoginService())->restoreSessionIfValid();
        }

        if (! $session->get('user_id')) {
            return null;
        }

        $target = (int) $session->get('profile_onboarding_completed') === 1
            ? '/dashboard'
            : '/profile/onboarding';

        return redirect()->to($target)->withCookies();
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        return null;
    }
}
