import type { TempTokensToken } from "~/schemas/public/TempTokens";

export const Upload = async ({
  files,
  getToken,
  from_admin,
}: {
  files: File[];
  getToken: ({ num }: { num: number }) => Promise<TempTokensToken[]>;
  from_admin: boolean;
}) => {
  const attachments = [];
  if (files.length === 0) {
    console.error("No files provided");
    return { status: false, attachments: [], error: "No files provided" };
  }
  if (files.length > 1) {
    const authTokens = await getToken({
      num: files.length,
    });

    if (authTokens.length !== files.length) {
      console.error(
        "Error: number of tokens does not match number of files",
        authTokens.length,
        files.length,
      );
      return {
        status: false,
        attachments: [],
        error: "Error: number of tokens does not match number of files",
      };
    }
    for (const file of files) {
      const attach = await uploadFile({
        file,
        token: authTokens.pop()!,
        from_admin,
      });
      attachments.push(attach);
    }
  } else {
    const authTokens = (
      await getToken({
        num: 1,
      })
    )[0];
    if (!authTokens) {
      console.error("Error: no token received");
      return {
        status: false,
        attachments: [],
        error: "Error: no token received",
      };
    }

    const attach = await uploadFile({
      file: files[0]!,
      token: authTokens,
      from_admin,
    });
    attachments.push(attach);
  }

  return { status: true, attachments };
};

const uploadFile = async ({
  file,
  token,
  from_admin,
}: {
  file: File;
  token: TempTokensToken;
  from_admin: boolean;
}) => {
  const formData = new FormData();
  formData.append("file", file);

  const response = await fetch(
    `/go-api/storage/upload?token=${token}&from_admin=${from_admin}`,
    {
      method: "POST",
      body: formData,
    },
  );

  if (!response.ok) {
    throw new Error(
      `Error uploading file: ${response.status} ${response.statusText}`,
    );
  }
  return response.text();
};
