import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { AccountResDto } from '@api/models';
import { AuthService } from '@core/services/auth.service';
import dayjs from 'dayjs';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class ExpiredGuard {
  constructor(
    public authService: AuthService,
    public router: Router,
  ) {}

  canActivate(): Observable<boolean> | boolean {
    return this.authService.currentUser.pipe(
      map((user: AccountResDto | null) => {
        if (!user) {
          this.router.navigate(['']);
          return false;
        }
        const userExpires = user.expireDate;
        if (!userExpires || dayjs().isBefore(userExpires)) {
          return true;
        } else {
          this.router.navigate(['']);
          return false;
        }
      }),
    );
  }
}
