import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';

import { CashlineApiService } from './cashline-api.service';
import {
  canAccessJourney,
  defaultJourneyId,
  isAdministratorSession,
  isSystemOwnerSession,
  resolveJourneyRoute
} from './uat-access.util';
import type { JourneyId } from '../journeys/journey.models';

export const journeyRouteGuard = (journeyId: JourneyId): CanActivateFn => {
  return () => {
    const api = inject(CashlineApiService);
    const router = inject(Router);

    const session = api.currentSession;
    if (!session) {
      return router.parseUrl('/login');
    }

    if (isAdministratorSession(session) || isSystemOwnerSession(session)) {
      return router.parseUrl('/internal/user-administration');
    }

    if (!canAccessJourney(session, journeyId)) {
      const target = resolveJourneyRoute(defaultJourneyId(session));
      return router.parseUrl(target);
    }

    return true;
  };
};

export const userAdministrationRouteGuard: CanActivateFn = () => {
  const api = inject(CashlineApiService);
  const router = inject(Router);
  const session = api.currentSession;

  if (!session) {
    return router.parseUrl('/login');
  }

  if (isAdministratorSession(session) || isSystemOwnerSession(session)) {
    return true;
  }

  const target = resolveJourneyRoute(defaultJourneyId(session));
  return router.parseUrl(target);
};

