"use server";

const apiUrl = process.env.NEXT_SERVER_API_URL;

export async function createVorlage(formData: FormData) {
  const printer = formData.get("printer") as string;
  const product_type = formData.get("product_type") as string;
  const height = Number(formData.get("height"));
  const width = Number(formData.get("width"));
  const coordinatesJson = formData.get("coordinates") as string;
  const coordinates = JSON.parse(coordinatesJson);

  const payload = {
    printer,
    product_type,
    height,
    width,
    coordinates,
  };

  try {
    const response = await fetch(
      `${apiUrl}/vorlageFlaechendruck/createWithCoordinates`,
      {
        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 product_type = formData.get("product_type") as string;
  const height = Number(formData.get("height"));
  const width = Number(formData.get("width"));
  const coordinatesJson = formData.get("coordinates") as string;
  const coordinates = JSON.parse(coordinatesJson);

  const payload = {
    id,
    printer,
    product_type,
    height,
    width,
    coordinates,
  };

  try {
    const response = await fetch(
      `${apiUrl}/vorlageFlaechendruck/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.");
  }
}
