import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  Params,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { AuthService } from '@core/services/auth.service';
import { Observable } from 'rxjs';
import { distinctUntilChanged, tap } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class IsLoggedGuard {
  constructor(
    private authService: AuthService,
    private router: Router,
  ) {}

  checkIfUserIsAuthenticated(params?: Params, redirect?: string) {
    return this.authService.isAuthenticated$.pipe(
      distinctUntilChanged(),
      tap((isAuth: boolean) => {
        if (!isAuth) {
          if (params && params['code'] && params['email']) {
            const queryParams: Params = {
              code: params['code'],
              email: params['email'],
              redirect,
            };
            this.router.navigate(['/login'], { queryParams });
          } else {
            if (redirect) {
              const queryParams: Params = { redirect };
              this.router.navigate(['/login'], {
                ...(queryParams['redirect'] !== '/' ? { queryParams } : {}),
              });
            } else {
              this.router.navigate(['/login']);
            }
          }
        }
      }),
    );
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): Observable<boolean> | Promise<boolean> | boolean {
    const url = state.url;
    const relativePath = url.split('?');
    return this.checkIfUserIsAuthenticated(route.queryParams, relativePath[0]);
  }
}
