import { LoaderFunction } from "@remix-run/node";
import { withAuth } from "~/auth/withAuth";

export const loader: LoaderFunction = withAuth(async ({ api, params, request }) => {
  const datasetId = params.datasetId!;
  try {
    const fileResponse = await api.dataset.datasetControllerDownloadDatasetRaw({
      datasetId,
    }) as any;

    // Clone the stream for logging
    const reader = fileResponse.raw.body.tee();
    const logStream = reader[0];
    const responseStream = reader[1];

    // Read and log the cloned stream
    const logReader = logStream.getReader();
    let chunks = [];
    let readResult;
    while (!(readResult = await logReader.read()).done) {
      const chunk = readResult.value;
      chunks.push(chunk);
    }
    const content = new TextDecoder().decode(Buffer.concat(chunks));

    return new Response(responseStream, {
      headers: {
        "Content-Disposition": fileResponse.raw.headers.get("Content-Disposition"),
        "Content-Type": fileResponse.raw.headers.get("Content-Type"),
      },
    });
  } catch (error) {
    console.error("Failed to download the file:", error);
    return new Response("Error downloading file", { status: 500 });
  }
});
