import { itDelete, itFetch, itPost } from "@/fetchHelpers";
import { getCookieValue } from "@/router/guards";
import type { CircleDocument, DocumentUploadData } from "@/types";

type FileData = {
  fields: Record<string, string>;
  url: string;
};

async function startFileUpload(fileData: DocumentUploadData, courseSessionId: number) {
  if (fileData === null || fileData.file === null) {
    return null;
  }
  return await itPost(`/api/core/document/start/`, {
    file_type: fileData.file.type,
    file_name: fileData.file.name,
    name: fileData.name,
    learning_sequence: fileData.learningSequence.id,
    course_session: courseSessionId,
  });
}

function uploadFile(fileData: FileData, file: File) {
  if (fileData.fields) {
    return s3Upload(fileData, file);
  } else {
    return directUpload(fileData, file);
  }
}

function directUpload(fileData: FileData, file: File) {
  const formData = new FormData();
  formData.append("file", file);

  const headers = {
    Accept: "application/json",
  } as HeadersInit;

  const options = {
    method: "POST",
    headers: headers,
    body: formData,
  };
  // @ts-ignore
  options.headers["X-CSRFToken"] = getCookieValue("csrftoken");

  handleUpload(fileData.url, options);
}

function s3Upload(fileData: FileData, file: File) {
  const formData = new FormData();
  for (const [name, value] of Object.entries(fileData.fields)) {
    formData.append(name, value);
  }

  formData.append("file", file);

  const options = Object.assign({
    method: "POST",
    body: formData,
  });

  return handleUpload(fileData.url, options);
}

function handleUpload(url: string, options: RequestInit) {
  return itFetch(url, options).then((response) => {
    return response.json().catch(() => {
      return Promise.resolve(null);
    });
  });
}

export async function uploadCircleDocument(
  data: DocumentUploadData,
  courseSessionId: number
): Promise<CircleDocument> {
  if (data.file === null) {
    throw new Error("No file selected");
  }

  const startData = await startFileUpload(data, courseSessionId);

  await uploadFile(startData, data.file);
  const response = await itPost(`/api/core/file/finish/`, {
    file_id: startData.file_id,
  });

  const newDocument: CircleDocument = {
    id: startData.id,
    name: data.name,
    file_name: data.file.name,
    url: response.url,
    course_session: courseSessionId,
    learning_sequence: data.learningSequence.id,
  };

  return Promise.resolve(newDocument);
}

export async function deleteCircleDocument(documentId: number) {
  return itDelete(`/api/core/document/${documentId}/`);
}
