import fetch from "node-fetch"


let extractUrl = ""
let importUrl = ""

if (process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_REF == "production") {
  extractUrl = "https://us-central1-festive-post-278020.cloudfunctions.net/extractColumns"
  importUrl = "https://us-central1-festive-post-278020.cloudfunctions.net/importSheet"
} else if (process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_REF == "master") {
  extractUrl = "https://us-central1-infill-staging.cloudfunctions.net/extractColumns"
  importUrl = "https://us-central1-infill-staging.cloudfunctions.net/importSheet"
} else if (process.env.NEXT_PUBLIC_USE_FIREBASE_EMULATORS == "true") {
  extractUrl = "http://localhost:5001/infill-development/us-central1/extractColumns"
  importUrl = "http://localhost:5001/infill-development/us-central1/importSheet"
} else {
  extractUrl = "https://us-central1-infill-development.cloudfunctions.net/extractColumns"
  importUrl = "https://us-central1-infill-development.cloudfunctions.net/importSheet"
}

export const extractColumns = async (data) => {
  let formData = new FormData()
  formData.append("data", data)

  let response = await fetch(extractUrl, {
    method: "POST",
    body: formData
  })

  let json = await response.json()

  if (json.error) {
    throw new Error(json.error)
  }

  return json
}

export const importSheet = async (file, schema) => {
  let formData = new FormData()
  formData.append("schema", JSON.stringify(schema))
  formData.append("data", file)
  formData.append("type", "CUSTOM")

  console.log("IMPORT SCHEMA: ", schema)

  let response = await fetch(importUrl, {
    method: "POST",
    body: formData
  })

  let json = await response.json()

  return json.importId
}