"use client";

import { useEffect } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useAuthStore } from "@/features/auth/stores/auth.store";

type Props = {
  /**
   * Absolute target path (no querystring). When omitted, the current pathname is transformed:
   * `/services/...` -> `/account/services/...`.
   */
  targetPath?: string;
};

export function RedirectAuthenticatedToAccountServices({ targetPath }: Props) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
  const hasCheckedAuth = useAuthStore(state => state.hasCheckedAuth);

  useEffect(() => {
    if (!hasCheckedAuth) return;
    if (!isAuthenticated) return;

    // Simple path transformation: /services/* → /account/services/*
    const nextPath =
      targetPath ??
      (pathname.startsWith("/services") ? `/account${pathname}` : "/account/services");

    const query = searchParams?.toString() ?? "";
    router.replace(query ? `${nextPath}?${query}` : nextPath);
  }, [hasCheckedAuth, isAuthenticated, pathname, router, searchParams, targetPath]);

  return null;
}
