"use server";
import { TComunas, TPrice } from "@/types";
import { getPropertyFromText, getScript } from "./helpers";

export const getPrices = async () => {
  try {
    const res = await fetch(`${process.env.API_URL}/api/get-prices`, {
      headers: {
        Authorization: `Bearer ${process.env.API_KEY}`,
      },
      cache: "no-store",
    });

    if (!res.ok) throw new Error("Hubo un error al cargar los precios.");
    const prices: TPrice[] = await res.json();
    return prices;
  } catch (error) {
    if (error instanceof Error) return error.message;
  }
};
export const getComunas = async () => {
  try {
    const res = await fetch(`${process.env.API_URL}/api/comunas`, {
      headers: {
        Authorization: `Bearer ${process.env.API_KEY}`,
      },
      cache: "no-store",
    });

    if (!res.ok) throw new Error("Hubo un error al cargar las comunas.");
    const comunas: TComunas = await res.json();
    return comunas;
  } catch (error) {
    return [];
  }
};

export const sendDataResponseText = async (url: string, data: { [x: string]: string | number }, token: string) => {
  try {
    const response = await fetch(`${process.env.API_URL}/api/${url}`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) {
      throw new Error("Hubo un error al enviar la información. <br/>Vuelva a intentarlo mas tarde.");
    }

    /* const responseJSON = await response.json(); */
    const responseText = await response.text();
    console.log(responseText);
    if (typeof responseText === "string") {
      const TOKEN = getPropertyFromText(responseText, token);
      const script = getScript(responseText);
      if (!TOKEN) throw new Error("Hubo un error al enviar la información. <br/>Vuelva a intentarlo mas tarde.");
      return { status: response.status, response: TOKEN, script };
    }
  } catch (error) {
    if (error instanceof Error) {
      return { error: error.message };
    }
  }
};

export const sendData = async (url: string, data: { [x: string]: string }, xml = false) => {
  try {
    const response = await fetch(`${process.env.API_URL}/api/${url}`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });
    /* console.log(response); */
    if (!response.ok) {
      let errorMessage;
      try {
        const errorData = await response.json();
        errorMessage = errorData?.error;
      } catch (err) {
        errorMessage = "Hubo un error al enviar la información. <br/>Vuelva a intentarlo mas tarde.";
      }
      throw new Error(errorMessage);
    }
    return { status: response.status, data: xml ? await response.text() : await response.json(), ok: response.ok };
  } catch (error) {
    if (error instanceof Error) {
      return { message: error.message };
    }
  }
};
