import { useQuery } from "@tanstack/react-query";
import {
  type DeveloperRequestStatus,
  fetchDeveloperRequestStatus,
} from "../../lib/devApi";

export type DeveloperAccessGateState = {
  hasDeveloperAccess: boolean;
  isDeveloperRequestPending: boolean;
  canRequestDeveloperAccess: boolean;
  isLoadingDeveloperAccessGate: boolean;
};

function isPrivilegedDeveloperRole(profileRole: string) {
  return (
    profileRole === "super_admin" ||
    profileRole === "rp_admin" ||
    profileRole === "tenant_admin"
  );
}

export function resolveDeveloperAccessGate(
  profileRole: string,
  requestStatus?: DeveloperRequestStatus,
): Omit<DeveloperAccessGateState, "isLoadingDeveloperAccessGate"> {
  const hasDeveloperAccess =
    isPrivilegedDeveloperRole(profileRole) || requestStatus === "approved";
  const isDeveloperRequestPending = requestStatus === "pending";
  const canRequestDeveloperAccess =
    profileRole === "user" && !hasDeveloperAccess && !isDeveloperRequestPending;

  return {
    hasDeveloperAccess,
    isDeveloperRequestPending,
    canRequestDeveloperAccess,
  };
}

export function shouldFetchDeveloperRequestStatus(profileRole: string) {
  return profileRole === "user";
}

export function shouldShowDeveloperAccessLoading(
  profileRole: string,
  isLoadingIdentity: boolean,
  isLoadingRequestStatus: boolean,
) {
  return (
    profileRole === "user" && (isLoadingIdentity || isLoadingRequestStatus)
  );
}

export function useDeveloperAccessGate({
  hasAccessToken,
  profileRole,
  tenantId,
  isLoadingIdentity = false,
}: {
  hasAccessToken: boolean;
  profileRole: string;
  tenantId?: string;
  isLoadingIdentity?: boolean;
}) {
  const shouldFetchRequestStatus =
    shouldFetchDeveloperRequestStatus(profileRole);
  const { data: requestStatus, isLoading: isLoadingRequestStatus } = useQuery({
    queryKey: ["developer-request", tenantId],
    queryFn: () => fetchDeveloperRequestStatus(tenantId),
    enabled: hasAccessToken && shouldFetchRequestStatus,
  });

  const resolvedGate = resolveDeveloperAccessGate(
    profileRole,
    requestStatus?.status,
  );

  return {
    ...resolvedGate,
    isLoadingDeveloperAccessGate: shouldShowDeveloperAccessLoading(
      profileRole,
      isLoadingIdentity,
      isLoadingRequestStatus,
    ),
  } satisfies DeveloperAccessGateState;
}
