import type { AuthSessionDTO } from '../types/generated/AuthSessionDTO';
import { RouteAccessPolicy } from './RouteAccessPolicy';
import { ReturnToSanitizer } from './ReturnToSanitizer';
import { RoutePathBuilder } from './RoutePathBuilder';
import { PathnameInterpreter } from './PathnameInterpreter';
import { SearchParamBuilder } from '../routing/search-params/SearchParamBuilder';

/**
 * AuthRedirectBuilder - Builds redirect URLs for authentication flows
 * 
 * Responsibilities:
 * - Build login redirect with sanitized returnTo parameter
 * - Build redirect away from auth pages based on user role
 * - Preserve locale from current path
 * 
 * Pure-ish (no server dependencies)
 */
export class AuthRedirectBuilder {
  constructor(
    private policy: RouteAccessPolicy,
    private sanitizer: ReturnToSanitizer,
    private pathBuilder: RoutePathBuilder,
    private interpreter: PathnameInterpreter
  ) {}

  /**
   * Build redirect URL to login page with returnTo parameter
   * 
   * @param currentPathname - The current URL pathname (can include locale)
   * @returns Redirect URL to login page with sanitized returnTo
   * 
   * Example:
   * - '/dashboard' → '/auth/login?returnTo=%2Fdashboard'
   * - '/de/dashboard' → '/de/auth/login?returnTo=%2Fdashboard'
   * - '/api/evil' → '/auth/login?returnTo=%2F' (sanitized)
   */
  toLogin({ currentPathname }: { currentPathname: string }): string {
    // Interpret current path to extract locale
    const { locale } = this.interpreter.interpret(currentPathname);
    
    // Build login path with locale
    const loginPath = this.pathBuilder.build('auth.login', {}, { locale });
    
    // Sanitize returnTo (use current path as input, fallback to root)
    const sanitizedReturnTo = this.sanitizer.sanitizeReturnTo(currentPathname, '/');

    return `${loginPath}${SearchParamBuilder.auth(sanitizedReturnTo)}`;
  }

  /**
   * Build redirect URL away from auth page based on user role
   * 
   * @param session - Current authentication session
   * @param currentPathname - The current URL pathname (can include locale)
   * @returns Redirect URL to role-appropriate home page
   * 
   * Example:
   * - driver role, '/auth/login' → '/dashboard'
   * - sponsor role, '/de/auth/login' → '/de/sponsor/dashboard'
   * - admin role, '/auth/login' → '/admin'
   * - no role, '/auth/login' → '/dashboard' (default)
   */
  awayFromAuthPage({
    session,
    currentPathname,
  }: {
    session: AuthSessionDTO;
    currentPathname: string;
  }): string {
    // Extract locale from current path
    const { locale } = this.interpreter.interpret(currentPathname);
    
    // Get role-appropriate route ID
    const role = session.user?.role;
    const routeId = this.policy.roleHomeRouteId(role ?? '');
    
    // Build path with locale
    return this.pathBuilder.build(routeId, {}, { locale });
  }
}
