import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AccessStore } from '@shared/application/access.store';
import { Capability } from '@shared/domain/capability';
import { SessionStore } from './application/session.store';

/** Route guard: only let authenticated users in; otherwise redirect to /login. */
export const authGuard: CanActivateFn = () => {
  const store = inject(SessionStore);
  const router = inject(Router);
  return store.isAuthenticated() ? true : router.createUrlTree(['/login']);
};

/**
 * Route guard factory (PRD-0002 §6): authenticated AND holding `capability`, else
 * redirect. No route in this app currently needs a capability gate — brief's
 * canApprove/canReject/canSend are per-action, not per-page (both actors land on
 * the same `/brief` page and see different actions) — so this exists as the
 * available building block for the day a route-level gate is needed, e.g. a future
 * approver-only page.
 */
export function capabilityGuard(capability: Capability): CanActivateFn {
  return () => {
    const session = inject(SessionStore);
    const access = inject(AccessStore);
    const router = inject(Router);
    return session.isAuthenticated() && access.can(capability)
      ? true
      : router.createUrlTree(['/login']);
  };
}
