"use server";

import { getToken } from "@/actions/cookies";
import { getUserLocale } from "@/services/locale";
import { refreshAccessToken } from "@/services/refresh-access-token";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

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

      if (response.status === 401) {
        //////// Refresh token
        const data = await refreshAccessToken();
        if (!data) {
          cookies().delete("token");
          cookies().delete("refresh_token");
          cookies().delete("vendor");
          cookies().delete("UD");
          redirect("/sign-in");
        }
        cookies().set({
          name: "token",
          value: data.access_token,
          path: "/",
          maxAge: 60 * 60 * 24 * 5,
          secure: true,
          sameSite: "none",
          httpOnly: true,
        });
        cookies().set({
          name: "UD",
          value: JSON.stringify({
            is_affiliate: data?.user?.is_affiliate,
            is_vendor: data?.user?.is_vendor,
          }),
          path: "/",
          maxAge: 60 * 60 * 24 * 30,
          secure: true,
          sameSite: "none",
          httpOnly: true,
        });
      } //////// End refresh token
    } else {
      response = await fetch(`${process.env.NEXT_PUBLIC_ENDPOINT}${endPoint}`, {
        method: "POST",
        body,
        headers: {
          "Accept-Language": locale,
          Accept: "application/json",
          ...headers,
        },
        ...config,
      });
    }
    code = response.status;
    const data = await response.json();

    if (!response.ok) {
      return { ...data, error: true, code };
    }
    return { ...data, error: false, code };
  } catch (error) {
    let parsedError = {};
    try {
      parsedError = JSON.parse(error);
    } catch {
      parsedError = { message: "Something went wrong", data: null };
    }

    return { ...parsedError, error: true, code };
  }
}
