import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"

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

  const res: any = await event.context.fetch('models/c_country', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    name: body.name,
    description: body.description,
    countryCode: body.countryCode,
    hasRegion: body.hasRegion,
    displaySequence: body.displaySequence,
    HasPostal_Add: body.hasPostal_Add,
    isAddressLinesLocalReverse: body.isAddressLinesLocalReverse,
    isAddressLinesReverse: body.isAddressLinesReverse,
    isPostcodeLookup: body.isPostcodeLookup,
    allowCitiesOutOfList: body.allowCitiesOutOfList,
    captureSequence: body.captureSequence,
    /*addressPrintFormat: body.addressPrintFormat,
    localAddressFormat: body.localAddressFormat,
    postalCodeFormat: body.postalCodeFormat,
    phoneFormat: body.phoneFormat,
    mediaSize: body.mediaSize,
    bankRoutingNoFormat: body.bankRoutingNoFormat,
    bankAccountNoFormat: body.bankAccountNoFormat,
    language: body.language,
    taxIDDigitGenerationClass: body.taxIDDigitGenerationClass,
    placeholderForAddress1: body.placeholderForAddress1,
    placeholderForAddress2: body.placeholderForAddress2,
    placeholderForAddress3: body.placeholderForAddress3,
    placeholderForAddress4: body.placeholderForAddress4,
    placeholderForAddress5: body.placeholderForAddress5,
    placeholderForPostal: body.placeholderForPostal,
    placeholderForAdditionalZip: body.placeholderForAdditionalZip,
    placeholderForCity: body.placeholderForCity,
    placeholderForComments: body.placeholderForComments,*/
    C_Currency_ID: {
      id: body.currencyId,
      tableName: 'C_Currency'
    },
    tableName: 'C_Country'
  })
  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) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch(error) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})