import { useWebAuth } from "@code/auth/web";
import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import { useMutation } from "convex/react";
import { useEffect, useState } from "react";

export interface PersonalOrganizationState {
  readonly error?: Error;
  readonly organizationId?: Id<"organizations">;
  readonly organizationName?: string;
}

/** Ensure the authenticated user has its personal tenancy boundary. */
export const usePersonalOrganization = (): PersonalOrganizationState => {
  const auth = useWebAuth();
  const userId = auth.status === "authenticated" ? auth.user.id : null;
  const ensurePersonalOrganization = useMutation(
    api.organizations.ensurePersonalOrganization
  );
  const [state, setState] = useState<{
    readonly error?: Error;
    readonly organizationId?: Id<"organizations">;
    readonly organizationName?: string;
    readonly userId: string;
  }>();

  useEffect(() => {
    if (!userId) {
      return;
    }

    let active = true;
    const bootstrapOrganization = async (): Promise<void> => {
      try {
        const organization = await ensurePersonalOrganization();
        if (active) {
          setState({
            organizationId: organization._id,
            organizationName: organization.name,
            userId,
          });
        }
      } catch (caughtError: unknown) {
        if (active) {
          setState({
            error:
              caughtError instanceof Error
                ? caughtError
                : new Error(String(caughtError)),
            userId,
          });
        }
      }
    };
    void bootstrapOrganization();

    return () => {
      active = false;
    };
  }, [ensurePersonalOrganization, userId]);

  if (!userId || state?.userId !== userId) {
    return {};
  }

  return {
    error: state.error,
    organizationId: state.organizationId,
    organizationName: state.organizationName,
  };
};
