import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import { customersService } from "@/services/customers.service";
import type {
  CreateCustomerDto,
  UpdateCustomerDto,
} from "@/types/customers";

const KEY = ["customers"] as const;

export const useCustomers = () =>
  useQuery({
    queryKey: KEY,
    queryFn: customersService.list,
  });

export const useCustomer = (id: string | undefined) =>
  useQuery({
    queryKey: [...KEY, "id", id],
    queryFn: () => customersService.getById(id!),
    enabled: Boolean(id),
  });

export const useCreateCustomer = () => {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (dto: CreateCustomerDto) => customersService.create(dto),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
  });
};

export const useUpdateCustomer = () => {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: UpdateCustomerDto }) =>
      customersService.update(id, dto),
    onSuccess: (_data, { id }) => {
      qc.invalidateQueries({ queryKey: KEY });
      qc.invalidateQueries({ queryKey: [...KEY, "id", id] });
    },
  });
};

export const useDeleteCustomer = () => {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => customersService.remove(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
  });
};
