import axios from 'axios'

const instance = axios.create()

export class BaseAuthService {
  token = ''
  baseUrl = ''
  promise: Promise<string> | null = null

  async getAuthToken(): Promise<string> {
    if (this.token) {
      return this.token
    }

    if (!this.token && this.promise) {
      this.token = await this.promise
      this.promise = null

      return this.token
    }

    this.promise = instance
      .get(`${this.baseUrl}/get_auth_token`, { withCredentials: true })
      .then(response => {
        this.token = response.data.authToken
        this.promise = null

        return response.data.authToken
      })

    return this.promise
  }
}
