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"
import strapiHelper from "../../../../utils/strapiHelper"

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

  let tableId: number = 0
  const res: any = await fetchHelper(event, `models/ad_table?$filter=${string.urlEncode(`TableName eq '${table}'`)}`, 'GET', token, null)
  if(res?.records?.[0]) {
    tableId = res.records[0].id
  } else {
    if(table === 'C_Order') {
      tableId = 259
    } else if(table === 'PO_Order') {
      tableId = 2592
    } else if(table === 'C_Invoice') {
      tableId = 318
    } else if(table === 'PO_Invoice') {
      tableId = 3182
    } else if(table === 'C_BPartner') {
      tableId = 291  //2109
    } else if(table === 'C_Payment') {
      tableId = 335
    } else if(table === 'PO_Payment') {
      tableId = 3352
    } else if(table === 'M_InOut') {
      tableId = 319
    } else if(table === 'PO_InOut') {
      tableId = 3192
    } else if(table === 'RS_InOut') {
      tableId = 3193
    } else if(table === 'RP_InOut') {
      tableId = 3194
    } else if(table === 'C_Channel') {
      tableId = 275
    } else if(table === 'C_Campaign') {
      tableId = 274
    } else if(table === 'M_Product') {
      tableId = 208
    } else if(table === 'R_Request') {
      tableId = 417
    } else if(table === 'M_Product') {
      tableId = 771
    } else if(table === 'M_RMA') {
      tableId = 661
    } else if(table === 'PO_RMA') {
      tableId = 6612
    } else if(table === 'AD_User') {
      tableId = 114
    } else if(table === 'Lead_User') {
      tableId = 1142
    } else if(table === 'External_User') {
      tableId = 1143
    }
  }

  const response: any = await strapiHelper(event, `ad-attachments?filters[AD_Table_ID][$eq]=${tableId}&filters[Record_ID][$eq]=${id}`, 'GET', null)
  if(response?.data?.[0]?.id) {
    data['Strapi_Attachment_ID'] = response.data[0].id
    data['Strapi_Attachment_documentId'] = response.data[0].documentId
    data['status'] = 200
    data['message'] = ''
  } else {
    const resp: any = await strapiHelper(event, `ad-attachments`, 'POST', {
      data: {
        AD_Table_ID: tableId,
        Record_ID: id,
        Record_UU: body.uid
      }
    })
    if(resp?.data) {
      data['Strapi_Attachment_ID'] = resp.data.id
      data['Strapi_Attachment_documentId'] = resp.data.documentId
      data['status'] = 200
      data['message'] = ''
    } else {
      data = resp ?? response ?? {status: 500}
    }
  }

  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: any) {
      errorHandlingHelper(err?.data ?? err, error?.data ?? error)
    }
  }

  return data
})