import { string } from 'alga-js'

const getToken = async (credential: any) => {
  const config = credential?.api ? credential : useRuntimeConfig()

  return await $fetch(config.api.dhlurl+'/account/auth/ropc/v1/token', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: `grant_type=password&username=${string.urlEncode(config.api.dhluser)}&password=${string.urlEncode(config.api.dhlpass)}&client_id=${string.urlEncode(config.api.dhlkey)}&client_secret=${string.urlEncode(config.api.dhlsecret)}`
  })
}

export default async function dhlBaseHelper(event: any, credential: any, url: string, method: string = 'GET', body: any) {
  const config = credential?.api ? credential : useRuntimeConfig()
  let token = getCookie(event, 'logship_bdhtl3') ?? ''
  
  let options: any = {}
  if(credential?.headers) {
    options = {
      ...options,
      headers: credential.headers,
    }
  } else {
    options = {
      ...options,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + token
      },
    }
  }
  if(body) {
    options = {
      ...options,
      body: body
    }
  }

  if(token === '') {
    const res = await getToken(credential)
    if(res?.access_token) {
      token = res.access_token
      setCookie(event, 'logship_bdhtl3', token)
    }
  }

  try {
    return await $fetch(String(config.api.dhlurl ?? '').replace('/parcel/de', '')+'/'+url, {
      method: method,
      ...options
    })
  } catch(err: any) {
    const res2 = await getToken(credential)
    if(res2?.access_token) {
      token = res2.access_token
      setCookie(event, 'logship_bdhtl3', token)
    }

    return await $fetch(String(config.api.dhlurl ?? '').replace('/parcel/de', '')+'/'+url, {
      method: method,
      ...options
    })
  }
  
}