const DEBUG = process.env.IDEMPIERE_DEBUG === '1' || process.env.IDEMPIERE_DEBUG === 'true'

export default async function fetchHelper(event: any, url: string, method: string = 'GET', token: string, body: any) {
  const config = useRuntimeConfig()
  const logshipToken = getCookie(event, 'logship_it')
  let options: any = {}
  if(token || logshipToken) {
    options = {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        Authorization: 'Bearer '+(token || logshipToken)
      }
    }
  }
  if(body) {
    options = {
      ...options,
      body: body
    }
  }

  const fullUrl = config.api.url+'/'+url

  if (DEBUG) {
    console.log('╔════════════════════════════════════════════════════════')
    console.log('║ iDEMPIERE API REQUEST')
    console.log('╠════════════════════════════════════════════════════════')
    console.log('║ Timestamp:', new Date().toISOString())
    console.log('║ Method:', method)
    console.log('║ URL:', fullUrl)
    console.log('║ Headers:', JSON.stringify({
      ...options.headers,
      Authorization: options.headers?.Authorization ? 'Bearer [REDACTED]' : undefined
    }, null, 2))
    if(body) {
      console.log('║ Body:', JSON.stringify(body, null, 2))
    }
    console.log('╚════════════════════════════════════════════════════════')
  }

  const startTime = Date.now()

  try {
    const response = await $fetch(fullUrl, {
      method: method,
      ...options
    })

    if (DEBUG) {
      const duration = Date.now() - startTime
      console.log('╔════════════════════════════════════════════════════════')
      console.log('║ iDEMPIERE API RESPONSE')
      console.log('╠════════════════════════════════════════════════════════')
      console.log('║ Timestamp:', new Date().toISOString())
      console.log('║ Method:', method)
      console.log('║ URL:', fullUrl)
      console.log('║ Duration:', duration, 'ms')
      console.log('║ Status: SUCCESS')
      console.log('║ Response:', JSON.stringify(response, null, 2))
      console.log('╚════════════════════════════════════════════════════════')
    }

    return response
  } catch (error: any) {
    if (DEBUG) {
      const duration = Date.now() - startTime
      console.log('╔════════════════════════════════════════════════════════')
      console.log('║ iDEMPIERE API ERROR')
      console.log('╠════════════════════════════════════════════════════════')
      console.log('║ Timestamp:', new Date().toISOString())
      console.log('║ Method:', method)
      console.log('║ URL:', fullUrl)
      console.log('║ Duration:', duration, 'ms')
      console.log('║ Status: ERROR')
      console.log('║ Error:', JSON.stringify({name: error?.name, message: error?.message, statusCode: error?.statusCode, data: error?.data}, null, 2))
      console.log('╚════════════════════════════════════════════════════════')
    }
    throw error
  }
}
