"use client";

import { useRef } from "react";
import { toast } from "sonner";
import { env } from "@/infrastructure/config/env";
import { useT } from "@/shared/i18n/client";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";

/**
 * Impersonation in one click: Fleet opens in a new tab already signed in as the account, through its token
 * login, which replaces any account already open there. The tab opens on the click itself (a tab opened once
 * the API has answered is blocked as a popup). The token travels after "#", so it never reaches a server log.
 */
export function useImpersonation(impersonate: (id: number) => Promise<{ token: string }>) {
  const t = useT();
  const tab = useRef<Window | null>(null);

  const mutation = useApiMutation(impersonate, {
    onSuccess: ({ token }) => {
      const url = `${env.fleetUrl}/fleet/token-login#token=${encodeURIComponent(token)}`;
      if (tab.current && !tab.current.closed) {
        tab.current.location.href = url;
      } else {
        window.open(url, "_blank", "noopener");
      }
      toast.success(t.common.impersonationOpened);
    },
    onError: () => tab.current?.close(),
  });

  return {
    loading: mutation.loading,
    impersonate: (id: number) => {
      tab.current = window.open("about:blank", "_blank");
      if (tab.current) tab.current.opener = null;
      void mutation.mutate(id);
    },
  };
}
