import { ChangeDetectionStrategy, Component, inject, OnInit } from "@angular/core";
import { RouteHistoryService } from "./services/route-history.service";
import { Router } from "@angular/router";
import { defaultRoute } from "../app.routes";
import { environment } from "../../environments/environment";

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: ''
})
export class DefaultRouteRedirectComponent implements OnInit {
  router = inject(Router);
  routeHistoryService = inject(RouteHistoryService);

  ngOnInit() {
    //if production environment then redirect to the default route
    if (environment.production) {
      this.router.navigateByUrl(defaultRoute);
      return;
    }

    //in development environment, redirect to the last visited route or the default route
    const currentUrl = this.router.url;
    const lastRoute = this.routeHistoryService.hasLastRoute()
      ? this.routeHistoryService.getLastRoute()
      : defaultRoute;

    if (currentUrl !== lastRoute)
      this.router.navigateByUrl(lastRoute);
  }
}
