'use client';

import { usePathname } from 'next/navigation';
import { useEffect } from 'react';

import { useCfgRouter, useQueryParams } from '@djangocfg/ui-nextjs/hooks';

import { authLogger } from '../utils/logger';

export interface UseAutoAuthOptions {
  onOTPDetected?: (otp: string) => void;
  cleanupUrl?: boolean;
  /** Paths where auto-auth should be active. Default: ['/auth'] */
  allowedPaths?: string[];
}

/**
 * Hook for automatic authentication from URL query parameters
 * Detects OTP from URL and triggers callback
 */
export const useAutoAuth = (options: UseAutoAuthOptions = {}) => {
  const { onOTPDetected, cleanupUrl = true, allowedPaths = ['/auth'] } = options;
  const queryParams = useQueryParams();
  const pathname = usePathname();
  const router = useCfgRouter();

  // Check if current path is in allowed paths
  const isAllowedPath = allowedPaths.some(path => pathname === path || pathname?.startsWith(path + '/'));

  const hasOTP = !!(queryParams.get('otp'));
  const isReady = !!pathname && hasOTP && isAllowedPath;

  useEffect(() => {
    if (!isReady) return;

    const queryOtp = queryParams.get('otp') as string;

    // Handle OTP detection - only on allowed paths to avoid conflicts with other pages
    // (e.g., /dashboard/device uses ?otp= for device authorization, not user auth)
    if (queryOtp && typeof queryOtp === 'string' && queryOtp.length === 6) {
      authLogger.info('OTP detected in URL on auth page:', queryOtp);
      onOTPDetected?.(queryOtp);
    }

    // Clean up URL to remove sensitive params for security
    if (cleanupUrl && queryOtp) {
      const cleanQuery = Object.fromEntries(queryParams.entries());
      delete cleanQuery.otp;
      const queryString = new URLSearchParams(cleanQuery).toString();
      router.push(queryString ? `${pathname}?${queryString}` : pathname);
    }
  }, [pathname, queryParams, onOTPDetected, cleanupUrl, router, isReady]);

  return {
    isReady,
    hasOTP,
    isAllowedPath,
  };
};
