import { Routes } from '@angular/router';
import { NotFoundComponent } from './_shared/not-found.component';
import { RedirectGuard } from './_shared/redirect.guard';
import { RedirectComponent } from './_shared/redirect.component';
import { DefaultRouteRedirectComponent } from './_shared/default-route-redirect.component';
import { InfoComponent } from './_shared/info.component';
import { TestComponent } from './_test/test.component';
import { inject } from '@angular/core';
import { AuthService } from './_shared/services/auth.service';
import { filter, map, take } from 'rxjs/operators';
// import app-specific components here:
import { MarketPriceComponent } from './market-price/market-price.component';
import { PriceIndexComponent } from './price-index/price-index.component';
import { PriceIndexPublicationComponent } from './price-index-publication/price-index-publication.component';

export const defaultRoute = 'MarketPrice';

//This guard waits for the auth check to complete before making redirect decisions,
export const oauthAuthGuard = () => {
  const authService = inject(AuthService);

  if (authService.authCheckComplete$.getValue() && authService.isLoggedIn())
    return true;

  if (authService.authCheckComplete$.getValue() && !authService.isLoggedIn()) {
    authService.login();
    return false;
  }

  return authService.authCheckComplete$.pipe(
    filter(complete => complete), // Wait until auth check is complete
    take(1), // Only take the first emission after completion
    map(() => {
      if (authService.isLoggedIn())
        return true;
      else {
        authService.login();
        return false; // Prevent Angular routing while redirecting
      }
    })
  );
};

/*
  do not add a path directly to AppComponent
  main.ts bootstraps to AppComponent which has a router-outlet that may then load a duplicate AppComponent
*/
export const routes: Routes = [
  { path: 'externalRedirect', canActivate: [RedirectGuard], component: RedirectComponent, data: { externalUrl: '' } },
  // add app-specific routes here:
  { path: 'MarketPrice', component: MarketPriceComponent, canActivate: [oauthAuthGuard] },
  { path: 'PriceIndex', component: PriceIndexComponent, canActivate: [oauthAuthGuard] },
  { path: 'PriceIndexPublication', component: PriceIndexPublicationComponent, canActivate: [oauthAuthGuard] },
  // end app-specific routes
  { path: 'Info', component: InfoComponent, canActivate: [oauthAuthGuard] },
  { path: '', component: DefaultRouteRedirectComponent, pathMatch: 'full' },
  { path: 'Test/:tag', component: TestComponent }, //view Test page to display a component based on the tag
  { path: 'Test', component: TestComponent }, //view blank Test page
  { path: '**', component: NotFoundComponent, data: { title: 'Not Found' } }
];
