import { inject } from '@angular/core';
import { NGXLogger } from 'ngx-logger';
import { ConfigService } from '@services/config.service';
import { UserService } from '@users/user.service';
import { SystemPreferencesService } from '@services/system-preferences.service';
import { UserPreferenceService } from '@users/user-preference.service';
import { LicenseService } from '@services/license.service';
import { IqserPermissionsService, LoadingService, TenantsService } from '@iqser/common-ui';
import { FeaturesService } from '@services/features.service';
import { GeneralSettingsService } from '@services/general-settings.service';
import { tap } from 'rxjs/operators';
import { firstValueFrom } from 'rxjs';
import { Roles } from '@users/roles';
import { DossiersChangesService } from '@services/dossiers/dossier-changes.service';
import { ResolveFn } from '@angular/router';
import { BASE_HREF } from '@iqser/common-ui/lib/utils';

function redirectToLastDossierTemplate(baseHref: string, tenant: string, lastDossierTemplate: string) {
    const lastUrlSegment = window.location.pathname.split('/').filter(Boolean).pop();
    if (['main', tenant, baseHref].includes(lastUrlSegment)) {
        window.location.assign(tenant + '/main/' + lastDossierTemplate);
    }
}

export const mainResolver: ResolveFn<void> = async () => {
    const logger = inject(NGXLogger);
    logger.info('[ROUTES] Main resolver started...');

    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 licenseService = inject(LicenseService);
    const loadingService = inject(LoadingService);
    const configService = inject(ConfigService);
    const userService = inject(UserService);
    const baseHref = inject(BASE_HREF);

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

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

    const lastDossierTemplate = userPreferenceService.getLastDossierTemplate();

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

    loadingService.stop();
    const currentUser = userService.currentUser;
    tenantsService.storeTenant(currentUser.email ?? currentUser.username);

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