import { makeRequest } from "@frontend/kitui";
import type { GetDiscountsResponse } from "@root/model/discount";
import { useUserStore } from "@root/stores/user";
import { parseAxiosError } from "@root/utils/parse-error";
import { enqueueSnackbar } from "notistack";
import useSWR from "swr";

const apiUrl = process.env.REACT_APP_DOMAIN + "/price";

export async function getDiscounts(userId: string | null) {
  if (userId === null) {
    return;
  }

  try {
    const discountsResponse = await makeRequest<never, GetDiscountsResponse>({
      url: `${apiUrl}/discount/user/${userId}`,
      method: "get",
      useToken: true,
    });

    return discountsResponse.Discounts;
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    throw new Error(`Ошибка получения списка скидок. ${error}`);
  }
}

export function useDiscounts(userId: string | null) {
  const { data } = useSWR("discounts", () => getDiscounts(userId), {
    keepPreviousData: true,
    onError: (error) => {
      if (!(error instanceof Error)) return;

      enqueueSnackbar(error.message, { variant: "error" });
    },
  });

  return data;
}
