import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { Tables } from "@xtablo/shared-types";
import { clientApi } from "../lib/api";

type ClientSessionResponse = {
  client: Tables<"clients">;
};

export function useClientSession() {
  return useQuery<Tables<"clients"> | null>({
    queryKey: ["client-session"],
    queryFn: async () => {
      try {
        const { data } = await clientApi.get<ClientSessionResponse>("/api/v1/client-auth/me");
        return data.client;
      } catch (error) {
        const status =
          typeof error === "object" &&
          error !== null &&
          "response" in error &&
          typeof error.response === "object" &&
          error.response !== null &&
          "status" in error.response &&
          typeof error.response.status === "number"
            ? error.response.status
            : null;

        if (status === 401) {
          return null;
        }

        throw error;
      }
    },
    retry: false,
  });
}

export function useRequestClientMagicLink() {
  return useMutation({
    mutationFn: async ({ email, redirectTo }: { email: string; redirectTo: string }) => {
      const { data } = await clientApi.post<{
        message: string;
        success: boolean;
      }>("/api/v1/client-auth/request-link", {
        email,
        redirectTo,
      });

      return data;
    },
  });
}

export function useClientLogout() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async () => {
      await clientApi.post("/api/v1/client-auth/logout");
    },
    onSuccess: () => {
      queryClient.setQueryData(["client-session"], null);
      queryClient.removeQueries({ queryKey: ["client-portal"] });
    },
  });
}
