import { inject, Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class RouteHistoryService {
  private readonly LAST_ROUTE_KEY = 'lastVisitedRoute';
  router = inject(Router);

  constructor() {
    // Subscribe to router events to save routes
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((event: NavigationEnd) => {
      // Get the full URL including query params
      const currentUrl = event.urlAfterRedirects;

      if (currentUrl !== '/')
        localStorage.setItem(this.LAST_ROUTE_KEY, currentUrl);
    });
  }

  getLastRoute(): string | null {
    return localStorage.getItem(this.LAST_ROUTE_KEY);
  }

  hasLastRoute(): boolean {
    const lastRoute = this.getLastRoute();
    return lastRoute !== undefined && lastRoute !== null && lastRoute !== '/';
  }
}
