import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root',
})
export class ListingCategoryGuard implements CanActivate {
  private apiBaseUrl = environment.apiBaseUrl;
  constructor(private http: HttpClient, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> {
    const id = route.paramMap.get('id');
    const url = `${this.apiBaseUrl}/bizmatch/listings/undefined/${id}`;

    return this.http.get<any>(url).pipe(
      map(response => {
        const category = response.listingsCategory;
        if (category === 'business') {
          return this.router.createUrlTree([`/details-business-listing/${id}`]);
        } else if (category === 'commercialProperty') {
          return this.router.createUrlTree([`/details-commercial-property-listing/${id}`]);
        } else {
          return this.router.createUrlTree(['/not-found']);
        }
      }),
      catchError(() => {
        return of(this.router.createUrlTree(['/not-found']));
      }),
    );
  }
}
