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

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 tenant = inject(GET_TENANT_FROM_PATH_FN)();
        const keycloakInstance = keycloakService.getKeycloakInstance();

        const queryParams = new URLSearchParams(window.location.search);
        const username = queryParams.get('username');
        const router = inject(Router);

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

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

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

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

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