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;

      // Don't store the root path
      if (currentUrl !== '/' && currentUrl !== '/Root') {
        localStorage.setItem(this.LAST_ROUTE_KEY, currentUrl);
      }
    });
  }

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

  hasLastRoute(): boolean {
    return !!this.getLastRoute();
  }
}
