import { string } from 'alga-js'

const getToken = async (credential: any) => {
  const config = {
    api: credential
  }

  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 dhlCustomHelper(event: any, credential: any, url: string, method: string = 'GET', body: any) {
  const config = {
    api: credential
  }
  let token = getCookie(event, 'logship_bdhtl2') ?? ''
  
  let options: any = {}
  if(body) {
    options = {
      ...options,
      body: body
    }
  }

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

  try {
    return await $fetch(config.api.dhlurl+'/'+url, {
      method: method,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + token
      },
      ...options
    })
  } catch(err: any) {
    const res2 = await getToken(credential)
    if(res2?.access_token) {
      token = res2.access_token
      setCookie(event, 'logship_bdhtl2', token)
    }

    return await $fetch(config.api.dhlurl+'/'+url, {
      method: method,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + token
      },
      ...options
    })
  }
  
}