"use client";

import { type Dispatch, useEffect, useRef } from "react";

import type { LoginStatus } from "@/data/schemas/auth";
import type { AuthEvent } from "@/stores/auth/auth-events";

export interface GuestLoginBootstrapState {
  hasInitialized: boolean;
  isLoading: boolean;
  loginStatus: LoginStatus;
}

export interface ShouldSubmitGuestLoginInput
  extends GuestLoginBootstrapState {
  alreadyRequested: boolean;
}

export interface UseGuestLoginBootstrapInput
  extends GuestLoginBootstrapState {
  dispatch: Dispatch<AuthEvent>;
}

export function shouldSubmitGuestLogin({
  alreadyRequested,
  hasInitialized,
  isLoading,
  loginStatus,
}: ShouldSubmitGuestLoginInput): boolean {
  if (!hasInitialized || isLoading) return false;
  if (loginStatus !== "notLoggedIn") return false;
  return !alreadyRequested;
}

export function useGuestLoginBootstrap({
  dispatch,
  hasInitialized,
  isLoading,
  loginStatus,
}: UseGuestLoginBootstrapInput): void {
  const guestLoginRequestedRef = useRef(false);

  useEffect(() => {
    if (!hasInitialized || isLoading) return;

    if (loginStatus !== "notLoggedIn") {
      guestLoginRequestedRef.current = false;
      return;
    }

    if (
      !shouldSubmitGuestLogin({
        alreadyRequested: guestLoginRequestedRef.current,
        hasInitialized,
        isLoading,
        loginStatus,
      })
    ) {
      return;
    }

    guestLoginRequestedRef.current = true;
    dispatch({ type: "AuthGuestLoginSubmitted" });
  }, [dispatch, hasInitialized, isLoading, loginStatus]);
}
