import { cache } from "react";
import { API_BASE_URL } from "@/config/const";
import { AboutResponse, Restaurant } from "../(Main)/about/types/Types";
import axios from "axios";

export const RESTAURANT_FETCH_TIMEOUT_MS = 10_000;

async function fetchRestaurant(slug: string): Promise<Restaurant> {
  try {
    const response = await axios.get<AboutResponse>(
      `${API_BASE_URL}/public/restaurants/${slug}`,
      {
        headers: {
          "Content-Type": "application/json",
          "X-SLUG": slug,
        },
        timeout: RESTAURANT_FETCH_TIMEOUT_MS,
      },
    );

    const data = response.data;

    if (!data.success || !data.data) {
      throw new Error("RESTAURANT_NOT_FOUND");
    }

    return data.data;
  } catch (error) {
    if (error instanceof Error && error.message === "RESTAURANT_NOT_FOUND") {
      throw error;
    }
    if (axios.isAxiosError(error) && error.response?.status === 404) {
      throw new Error("RESTAURANT_NOT_FOUND");
    }
    throw new Error(`Failed to fetch restaurant data: ${error}`);
  }
}

export const getRestaurant = cache(fetchRestaurant);
