import { string } from 'alga-js'
import refreshTokenHelper from "../../../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../../../utils/errorHandlingHelper"
import fetchHelper from "../../../../../utils/fetchHelper"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  if(body.id) {
    data['c_bp_group_id'] = body.partnerGroupId
    const newFilter = string.urlEncode(`Name neq '${body.partnerGroup}'`)
    const resp: any = await fetchHelper(event, `models/c_bp_group?$filter=${newFilter}&$orderby=${string.urlEncode('id asc')}`, 'GET', token, null)
    if(resp?.records?.[0]) {
      data['c_bp_group_id'] = resp.records[0].id
    }
    const res: any = await fetchHelper(event, 'models/c_bpartner/'+body.id, 'PUT', token, {
      C_BP_Group_ID: {
        id: data['c_bp_group_id'],
        tableName: 'C_BP_Group'
      },
      tableName: 'c_bpartner'
    })
    if(res) {
      data = res
      data['status'] = 200
      data['message'] = ''
    }
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = {}

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    if(err.status >= 500 || err.statusCode >= 500) {
      data = {
        status: err.status || err.statusCode,
        message: err.detail || err.details || err.message || err.statusMessage
      }
    } else {
    try {
        let authToken: any = await refreshTokenHelper(event)
        data = await handleFunc(event, authToken)
      } catch(error: any) {
        data = {
          status: error.status || error.statusCode || 500,
          message: error.detail || error.details || error.message || error.statusMessage
        }
      }
    }
  }

  return data
})