import { inject, Injectable } from '@angular/core';
import { UrlTree, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { GetUserDetailsAction } from './../../shared/action/account.action';
import { AuthService } from './../../shared/services/auth.service';

@Injectable({
  providedIn: 'root',
})
export class CheckoutGuard {
  private store = inject(Store);
  private router = inject(Router);
  private authService = inject(AuthService);

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    // Store the attempted URL for redirecting after login
    this.authService.redirectUrl = state.url;

    if (this.store.selectSnapshot(state => state.auth && state.auth.access_token)) {
      this.store.dispatch(new GetUserDetailsAction()).subscribe({
        complete: () => {
          return true;
        },
      });
    } else {
      if (this.store.selectSnapshot(state => state.setting).setting.activation.guest_checkout) {
        // Redirect to the login page
        if (this.store.selectSnapshot(state => state.cart.is_digital_only)) {
          return this.router.createUrlTree(['/auth/login']);
        }
      } else {
        return this.router.createUrlTree(['/auth/login']);
      }
    }

    return true;
  }
}
