import { inject } from '@angular/core';
import { Router, RouterStateSnapshot } from '@angular/router';
import { AsyncGuard, IqserPermissionsService, LoadingService } from '@iqser/common-ui';
import { TenantsService } from '@iqser/common-ui/lib/tenants';
import { BASE_HREF } from '@iqser/common-ui/lib/utils';
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';

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

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

        console.log('main guard');

        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 baseHref = inject(BASE_HREF);

        const generalConfig$ = inject(GeneralSettingsService).getGeneralConfigurations();
        const updatedDisplayName$ = generalConfig$.pipe(tap(config => configService.updateDisplayName(config.displayName)));

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

        const lastDossierTemplate = userPreferenceService.getLastDossierTemplate();

        if (lastDossierTemplate) {
            await redirectToLastDossierTemplate(router, state, baseHref, tenantsService.activeTenantId, lastDossierTemplate);
        }

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

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

        return true;
    };
}
