"use server";

import { getToken } from "@/actions/cookies";
import { revalidatePath } from "next/cache";

export default async function deleteData({
  endPoint,
  locale = "ar",
  headers = {},
  pathToRevalidate,
  ...config
}) {
  let code;
  let response;
  const token = await getToken();
  try {
    if (token) {
      response = await fetch(`${process.env.NEXT_PUBLIC_ENDPOINT}${endPoint}`, {
        method: "DELETE",
        headers: {
          Authorization: ` Bearer ${token}`,
          "Accept-Language": locale,
          Accept: "application/json",
          ...headers,
        },
        ...config,
      });
    } else {
      response = await fetch(`${process.env.NEXT_PUBLIC_ENDPOINT}${endPoint}`, {
        method: "DELETE",
        headers: {
          "Accept-Language": locale,
          Accept: "application/json",
          ...headers,
        },
        ...config,
      });
    }

    code = response.status;

    if (!response.ok) {
      const errorObject = await response.json();
      throw new Error(JSON.stringify(errorObject));
    }
    const data = await response.json();
    //  need to update the revalidate

    revalidatePath(pathToRevalidate);

    return { ...data, error: false, code };
  } catch (error) {
    let parsedError;
    try {
      parsedError = JSON.parse(error.message);
    } catch {
      parsedError = { message: "'Internal Server Error'", details: error };
    }
    return { ...parsedError, error: true, code };
  }
}
