"use server";
import { main, OrderData } from "./orderUpdateBillbee";

export async function uploadFile(formData: FormData) {
  const file = formData.get("file") as File;

  // Check if the file is a CSV
  if (!file || (file.type !== "text/csv" && !file.name.endsWith(".csv"))) {
    return { message: "Ausgewählte Datei ist keine CSV", status: false };
  }
  const arrayBuffer = await file.arrayBuffer();
  const buffer = new Uint8Array(arrayBuffer);

  // Decode the buffer to a string
  const decoder: TextDecoder = new TextDecoder("utf-8");
  const csvContent: string = decoder.decode(buffer);

  // Determine the delimiter (comma or semicolon)
  const delimiter = csvContent.includes(";") ? ";" : ",";

  // Parse the CSV content using the detected delimiter
  const rows: string[][] = csvContent
    .split("\n")
    .map((row) => row.split(delimiter));

  const requiredHeaders = ["Bestellnummer", "Sendungsnummer"];
  const headers: string[] = rows[0].map((header) =>
    header.trim().replace(/\r/g, "")
  );
  // Check if CSV containes required Headers
  const allHeadersPresent: boolean = requiredHeaders.every((header) =>
    headers.includes(header)
  );
  if (!allHeadersPresent) {
    return {
      message:
        'CSV enthält nicht die notwendigen Header "Bestellnummer" und "Sendungsnummer"',
      status: false,
    };
  }

  // Get the indices of the required headers
  const indices: number[] = requiredHeaders.map((header) =>
    headers.indexOf(header)
  );

  // Create an array of objects with only the required headers
  const filteredData: OrderData[] = rows.slice(1).map((row) => {
    const orderData: OrderData = {
      Bestellnummer: row[indices[0]] ? row[indices[0]].trim() : null,
      Sendungsnummer: row[indices[1]] ? row[indices[1]].trim() : null,
    };
    return orderData;
  });

  return { data: await main(filteredData), status: true };
}
