import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuthToken } from "../hooks/use-root-data";
import {
  SellerCourierCreate,
  SellerCourierUpdate,
} from "../../src/api/types";
import { createSellerCourierManagementApi, createCourierManagementApi } from "~/utils/api-client-factory";

export function useServiceGetCouriers(sellerId: string) {
  const token = useAuthToken();
  const response = useQuery({
    enabled: !!token && !!sellerId,
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["getCouriersService", sellerId],
    queryFn: async () => {
      if (!token) throw new Error("Authentication token is required");

      try {
        return await createSellerCourierManagementApi(token).apiOrderV1SellerCouriersSellerList({
          seller: sellerId,
        });
      } catch (error) {
        console.error("Error fetching couriers:", error);
        throw error;
      }
    },
  });

  return { ...response };
}

export function useGetAllCouriers() {
  const token = useAuthToken();
  const response = useQuery({
    enabled: !!token,
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["getAllCouriers"],
    queryFn: async () => {
      if (!token) throw new Error("Authentication token is required");

      try {
        return await createCourierManagementApi(token).apiOrderV1CouriersList();
      } catch (error) {
        console.error("Error fetching all couriers:", error);
        throw error;
      }
    },
  });

  return { ...response };
}

export function useCreateSellerCourier() {
  const token = useAuthToken();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (data: SellerCourierCreate) => {
      if (!token) throw new Error("Authentication token is required");

      try {
        return await createSellerCourierManagementApi(token).apiOrderV1SellerCouriersCreate({
          data,
        });
      } catch (error) {
        console.error("Error creating seller courier:", error);
        throw error;
      }
    },
    onSuccess: () => {
      // Invalidate and refetch seller couriers
      queryClient.invalidateQueries({ queryKey: ["getCouriersService"] });
    },
  });
}

export function useDeleteSellerCourier() {
  const token = useAuthToken();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string) => {
      if (!token) throw new Error("Authentication token is required");

      try {
        return await createSellerCourierManagementApi(token).apiOrderV1SellerCouriersDeleteDelete({
          id,
        });
      } catch (error) {
        console.error("Error deleting seller courier:", error);
        throw error;
      }
    },
    onSuccess: () => {
      // Invalidate and refetch seller couriers
      queryClient.invalidateQueries({ queryKey: ["getCouriersService"] });
    },
  });
}

export function useUpdateSellerCourier() {
  const token = useAuthToken();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      id,
      data,
    }: {
      id: string;
      data: SellerCourierUpdate;
    }) => {
      if (!token) throw new Error("Authentication token is required");

      try {
        return await createSellerCourierManagementApi(token).apiOrderV1SellerCouriersPartialUpdate({
          id,
          data,
        });
      } catch (error) {
        console.error("Error updating seller courier:", error);
        throw error;
      }
    },
    onSuccess: () => {
      // Invalidate and refetch seller couriers
      queryClient.invalidateQueries({ queryKey: ["getCouriersService"] });
    },
  });
}
