import { useQuery } from "@tanstack/react-query";
import {
  type DeveloperAccessStatus,
  fetchDeveloperRequestStatus,
} from "../../lib/devApi";
import {
  type DeveloperAccessPage,
  hasDeveloperAccessForPages,
  isDeveloperRequestPendingForPages,
} from "./developerAccessPages";

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

export function resolveDeveloperAccessGate(
  profileRole: string,
  accessStatus?: DeveloperAccessStatus,
  requiredPages: DeveloperAccessPage[] = ["overview"],
): Omit<
  DeveloperAccessGateState,
  "isLoadingDeveloperAccessGate" | "isTenantContextMissing"
> {
  const hasDeveloperAccess =
    profileRole === "super_admin" ||
    hasDeveloperAccessForPages(accessStatus?.approvedPages, requiredPages);
  const isDeveloperRequestPending = isDeveloperRequestPendingForPages(
    accessStatus?.pendingPages,
    requiredPages,
  );
  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,
  requiredPages = ["overview"],
  isLoadingIdentity = false,
}: {
  hasAccessToken: boolean;
  profileRole: string;
  tenantId?: string;
  requiredPages?: DeveloperAccessPage[];
  isLoadingIdentity?: boolean;
}) {
  const shouldFetchRequestStatus =
    shouldFetchDeveloperRequestStatus(profileRole);
  const isTenantContextMissing = !tenantId?.trim();
  const { data: requestStatus, isLoading: isLoadingRequestStatus } = useQuery({
    queryKey: ["developer-request", tenantId],
    queryFn: () => fetchDeveloperRequestStatus(tenantId),
    enabled: hasAccessToken && shouldFetchRequestStatus,
  });

  const resolvedGate = resolveDeveloperAccessGate(
    profileRole,
    requestStatus,
    requiredPages,
  );

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