import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { inject } from '@angular/core';
import { NGXLogger } from 'ngx-logger';
import { keycloakInitializer, KeycloakStatusService, TenantsService } from '@iqser/common-ui/lib/tenants';
import { KeycloakService } from 'keycloak-angular';
import { UserService } from '@users/user.service';
import { LicenseService } from '@services/license.service';
import { AsyncGuard } from '@iqser/common-ui';
import jwt_decode from 'jwt-decode';

export interface JwtToken {
    auth_time: number;
    iat: number;
}

export function ifLoggedIn(): AsyncGuard {
    return async (route: ActivatedRouteSnapshot) => {
        const logger = inject(NGXLogger);
        logger.info('[ROUTES] Check if can activate route', route);

        const tenantsService = inject(TenantsService);
        const keycloakService = inject(KeycloakService);
        const usersService = inject(UserService);
        const licenseService = inject(LicenseService);
        const keycloakStatusService = inject(KeycloakStatusService);

        const keycloakInstance = keycloakService.getKeycloakInstance();
        const tenant = route.paramMap.get('tenant');
        const queryParams = new URLSearchParams(window.location.search);
        const username = queryParams.get('username');

        if (!keycloakInstance) {
            if (!tenant) {
                logger.error('[ROUTES] No tenant found, something is wrong...');
                return inject(Router).navigate(['/']);
            }

            logger.info('[KEYCLOAK] Keycloak init...');
            await keycloakInitializer(tenant);
            logger.info('[KEYCLOAK] Keycloak init done!');
            await tenantsService.selectTenant(tenant);
            await usersService.initialize();
            await licenseService.loadLicenses();

            const token = await keycloakService.getToken();
            if (token) {
                const jwtToken = jwt_decode(token) as JwtToken;
                const authTime = (jwtToken.auth_time || jwtToken.iat).toString();
                localStorage.setItem('authTime', authTime);
            }
        }

        const isLoggedIn = await keycloakService.isLoggedIn();

        if (isLoggedIn) {
            logger.info('[ROUTES] Is logged in, continuing');
            return true;
        }

        logger.warn('[ROUTES] Redirect to login');
        keycloakStatusService.createLoginUrlAndExecute(username);
        return false;
    };
}
