import type { ReactNode } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { useAuthStore } from '@/stores/authStore'

interface MustChangePasswordGateProps {
  children: ReactNode
}

/**
 * Router guard for the "must change password" flow (UDT-008).
 *
 * If the authenticated user has mustChangePassword=true and is NOT already
 * on /perfil/contrasena, redirects them there.
 *
 * Place this INSIDE ProtectedRoute so it only fires for authenticated users.
 * The /perfil/contrasena route itself must NOT be wrapped with this gate
 * to avoid redirect loops.
 */
export function MustChangePasswordGate({ children }: MustChangePasswordGateProps) {
  const user = useAuthStore((s) => s.user)
  const location = useLocation()

  if (user?.mustChangePassword && location.pathname !== '/perfil/contrasena') {
    return <Navigate to="/perfil/contrasena" replace />
  }

  return <>{children}</>
}
