"use server";

const apiUrl = process.env.NEXT_SERVER_API_URL;

export async function createVorlage(formData: FormData) {
  const printer = formData.get("printer") as string;
  const height = Number(formData.get("height"));
  const width = Number(formData.get("width"));
  const articleTypes = formData.get("articleTypes") as string;

  const payload = {
    printer,
    height,
    width,
    articleTypes
  };

  try {
    const response = await fetch(
      `${apiUrl}/VorlageRollenDruck/createRollenDruckVorlage`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
        cache: "no-store",
      }
    );

    if (!response.ok) {
      console.error("Response status:", response.status);
      throw new Error("Failed to submit form");
    }
  } catch (error) {
    console.error("Error submitting form:", error);
    throw new Error("An error occurred while submitting the form.");
  }
}

export async function alterVorlage(formData: FormData) {
  const id = Number(formData.get("id"));
  const printer = formData.get("printer") as string;
  const height = Number(formData.get("height"));
  const width = Number(formData.get("width"));
  const articleTypes = formData.get("articleTypes") as string;

  const payload = {
    id,
    printer,
    height,
    width,
    articleTypes
  };

  try {
    const response = await fetch(
      `${apiUrl}/VorlageRollenDruck/alterVorlage`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
        cache: "no-store",
      }
    );

    if (!response.ok) {
      console.error("Response status:", response.status);
      throw new Error("Failed to submit form");
    }
  } catch (error) {
    console.error("Error submitting form:", error);
    throw new Error("An error occurred while submitting the form.");
  }
}

export async function addDupliArtikel(fromData: FormData) {
  const artikelTyp = fromData.get("ArtikelTyp") as string;

  const payload = {
    product_type: artikelTyp,
  };

  try {
    const response = await fetch(
      `${apiUrl}/VorlageRollenDruck/addDupliArtikel`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
        cache: "no-store",
      }
    );

    if (!response.ok) {
      console.error("Response status:", response.status);
      throw new Error("Failed to submit form");
    }
  } catch (error) {
    console.error("Error submitting form:", error);
    throw new Error("An error occurred while submitting the form.");
  }
}
