import toast from "react-hot-toast"
import { RIGOBOT_HOST, DEV_MODE } from "./constants"
import axios, { AxiosError } from "axios"

type TInteractiveCreationInputs = {
  courseInfo: string
  prevInteractions: string
}

export const publicInteractiveCreation = async (
  inputs: TInteractiveCreationInputs,
  token: string,
  purposeSlug: string,
  publicRequest: boolean = true
): Promise<any | null> => {
  try {
    const response = await axios.post(
      `${RIGOBOT_HOST}/v1/prompting${
        publicRequest ? "/public" : ""
      }/completion/${DEV_MODE ? "39" : "390"}/`,
      {
        inputs: inputs,
        include_purpose_objective: true,
        execute_async: false,
        purpose_slug: purposeSlug,
      },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Token ${token}`,
        },
      }
    )

    return response.data
  } catch (error: unknown) {
    const err = error as AxiosError
    console.log("error", err)

    if (err.response?.status === 403) {
      toast.error("You've reached the limit. Please log in to continue.")
    } else {
      toast.error("Something went wrong while generating the course.")
    }

    return null
  }
}

export const isHuman = async (token: string) => {
  try {
    const body = {
      access_token: token,
    }
    const response = await axios.post(
      `${RIGOBOT_HOST}/v1/auth/verify/humanity`,
      body,
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    )

    return {
      human: response.status === 200,
      message: response.data.message,
      token: response.data.public_access_token,
    }
  } catch (error) {
    console.error(error)
    return { human: false, message: error, token: null }
  }
}
