import { inject, Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { IqserPermissionsService } from '@iqser/common-ui';
import { IqserRoleGuard } from '@iqser/common-ui/lib/users';
import { UserService } from '@users/user.service';
import { NGXLogger } from 'ngx-logger';

@Injectable({
    providedIn: 'root',
})
export class RedRoleGuard extends IqserRoleGuard {
    protected readonly _permissionsService = inject(IqserPermissionsService);
    protected readonly _userService = inject(UserService);
    protected readonly _logger = inject(NGXLogger);

    async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        const currentUser = this._userService.currentUser;

        if (!currentUser?.hasAnyRole) {
            this._logger.warn('[GUARD] User has no roles, redirect to auth-error');
            await this._router.navigate([`/${this._tenantsService.activeTenantId}/auth-error`]);
            this._loadingService.stop();
            return false;
        }

        // we have at least 1 RED Role -> if it's not user he must be an admin
        if (currentUser.isUserAdmin && !currentUser.isAdmin && state.url.includes('admin') && !state.url.includes('users')) {
            this._logger.warn('[GUARD] Redirect to users page');
            await this._router.navigate([`/${this._tenantsService.activeTenantId}/main/admin/users`]);
            return false;
        }

        if (
            currentUser.isUserAdmin &&
            !currentUser.isAdmin &&
            !currentUser.isUser &&
            !(state.url.includes('/main/admin/users') || state.url.includes('/main/account'))
        ) {
            await this._router.navigate([`/${this._tenantsService.activeTenantId}/main/admin/users`]);
            return false;
        }

        if (route.data.requiredRoles) {
            if (currentUser.hasAny(route.data.requiredRoles)) {
                return true;
            }
            if (!currentUser.isUser) {
                await this._router.navigate([`/${this._tenantsService.activeTenantId}/main/admin`]);
            } else {
                this._logger.warn('[GUARD] Redirect to tenant route');
                await this._router.navigate([`/${this._tenantsService.activeTenantId}`]);
            }
            return false;
        }

        return true;
    }
}
