import { inject } from '@angular/core';
import { Router, RouterStateSnapshot } from '@angular/router';
import { AsyncGuard, IqserPermissionsService, LanguageService, LoadingService } from '@iqser/common-ui';
import { TenantsService } from '@iqser/common-ui/lib/tenants';
import { ConfigService } from '@services/config.service';
import { DossiersChangesService } from '@services/dossiers/dossier-changes.service';
import { FeaturesService } from '@services/features.service';
import { GeneralSettingsService } from '@services/general-settings.service';
import { SystemPreferencesService } from '@services/system-preferences.service';
import { Roles } from '@users/roles';
import { UserPreferenceService } from '@users/user-preference.service';
import { NGXLogger } from 'ngx-logger';
import { firstValueFrom } from 'rxjs';
import { tap } from 'rxjs/operators';
import { APP_BASE_HREF } from '@angular/common';
import { getCurrentUser } from '@users/user.service';

async function redirectToLastDossierTemplate(router: Router, state: RouterStateSnapshot, baseHref: string, lastDossierTemplate: string) {
    const lastUrlSegment = window.location.pathname.split('/').filter(Boolean).pop();
    if (['main', baseHref].includes(lastUrlSegment) && !state.url.includes(lastDossierTemplate)) {
        await router.navigate(['main', lastDossierTemplate]);
    }
}

export function mainGuard(): AsyncGuard {
    return async (_, state) => {
        const logger = inject(NGXLogger);
        logger.info('[ROUTES] Main resolver started...');

        const router = inject(Router);
        inject(FeaturesService).loadConfig();
        if (inject(IqserPermissionsService).has(Roles.dossiers.read)) {
            inject(DossiersChangesService).initialize();
        }

        const systemPreferencesService = inject(SystemPreferencesService);
        const userPreferenceService = inject(UserPreferenceService);
        const tenantsService = inject(TenantsService);
        const loadingService = inject(LoadingService);
        const configService = inject(ConfigService);
        const languageService = inject(LanguageService);
        const baseHref = inject(APP_BASE_HREF);

        const generalConfig$ = inject(GeneralSettingsService).getGeneralConfigurations();
        const updatedDisplayName$ = generalConfig$.pipe(tap(config => configService.updateDisplayName(config.displayName)));
        const currentUser = getCurrentUser();
        const isUsersAdminOnly = currentUser.isUserAdmin && !currentUser.isUser && !currentUser.isManager;

        await Promise.all([
            systemPreferencesService.loadPreferencesIfNeeded(),
            userPreferenceService.reload(),
            firstValueFrom(updatedDisplayName$),
        ]);

        await languageService.setInitialLanguage();
        const lastDossierTemplate = userPreferenceService.getLastDossierTemplate();

        if (lastDossierTemplate && !isUsersAdminOnly) {
            await redirectToLastDossierTemplate(router, state, baseHref, lastDossierTemplate);
        }

        loadingService.stop();
        tenantsService.storeTenant();

        logger.info('[ROUTES] Main guard finished!');

        return true;
    };
}
