"use server";
//import { promises as fs } from "fs";
const apiUrl = process.env.NEXT_SERVER_API_URL;
//const sharedFolder = process.env.SHARED_FOLDER;

export async function getVorlagen() {
  try {
    const response = await fetch(
      `${apiUrl}/vorlageFlaechendruck/getAllFlaechendruckVorlagen`
    );
    if (!response.ok) {
      console.error("Response status:", response.status);
      throw new Error("Failed to fetch vorlagen");
    }
    return await response.json();
  } catch (error) {
    console.error("Error fetching vorlagen:", error);
    throw new Error("An error occurred while fetching vorlagen.");
  }
}

export async function generateFlaechendruck(formData: FormData) {
  const vorlageIds = formData.getAll("vorlageIds") as string[];
  const requestBody = {
    rootDirectory: "Orders",
    vorlageIds: vorlageIds,
  };

  const response = await fetch(`${apiUrl}/vorlageFlaechendruck/generate`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(requestBody),
    cache: "no-store",
  });
  if (!response.ok) {
    const body = await response.text().catch(() => null);
    const msg = body ? body : `HTTP ${response.status}`;
    return { message: msg, status: false };
  } else {
    return { message: "Erfolgreiche Flächendruckgenerierung!", status: true };
  }
}
