import { ActivatedRouteSnapshot, CanActivateFn, Router } from '@angular/router';
import { inject } from '@angular/core';
import { NGXLogger } from 'ngx-logger';
import { KeycloakService } from 'keycloak-angular';

export function ifNotLoggedIn(): CanActivateFn {
    return async (route: ActivatedRouteSnapshot) => {
        const logger = inject(NGXLogger);
        const router = inject(Router);
        const keycloakService = inject(KeycloakService);

        const isLoggedIn = await keycloakService.isLoggedIn();

        if (!isLoggedIn) {
            logger.info('[ROUTES] Not logged in, continuing to selected route');
            return true;
        }

        const tenant = route.paramMap.get('tenant') || keycloakService.getKeycloakInstance().realm;
        if (!tenant) {
            logger.error('[ROUTES] Tenant not found in route or keycloak realm');
            return false;
        }

        logger.warn('[ROUTES] Is logged in for ' + tenant + ', redirecting to /' + tenant);
        await router.navigate([tenant]);
        return false;
    };
}
