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 config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  let newObjValue = {}
  if(body.docTypeId) {
    newObjValue = {...newObjValue, 
      C_DocType_ID: {
        id: body.docTypeId,
        tableName: 'C_DocType'
      }
    }
  }
  if(body.docStatusId) {
    newObjValue = {...newObjValue, 
      DocStatus: {
        id: body.docStatusId
      }
    }
  }
  if(body.postingTypeId) {
    newObjValue = {...newObjValue, 
      PostingType: {
        id: body.postingTypeId
      }
    }
  }
  if(body.acctSchemaId) {
    newObjValue = {...newObjValue, 
      C_AcctSchema_ID: {
        id: body.acctSchemaId,
        tableName: 'C_AcctSchema'
      }
    }
  }
  if(body.categoryId) {
    newObjValue = {...newObjValue, 
      GL_Category_ID: {
        id: body.categoryId,
        tableName: 'GL_Category'
      }
    }
  }
  if(body.periodId) {
    newObjValue = {...newObjValue, 
      C_Period_ID: {
        id: body.periodId,
        tableName: 'C_Period'
      }
    }
  }
  if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        id: body.currencyId,
        tableName: 'C_Currency'
      }
    }
  }
  if(body.conversionTypeId) {
    newObjValue = {...newObjValue, 
      C_ConversionType_ID: {
        id: body.conversionTypeId,
        tableName: 'C_ConversionType'
      }
    }
  }

  const res: any = await fetchHelper(event, 'models/gl_journal', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    description: body.description,
    documentNo: body.documentNo,
    isPrinted: body.isPrinted,
    dateDoc: body.dateDoc,
    dateAcct: body.dateAcct,
    totalDr: body.totalDr,
    totalCr: body.totalCr,
    isApproved: body.isApproved,
    currencyRate: body.currencyRate,
    controlAmt: body.controlAmt,
    processed: body.processed,
    ...newObjValue,
    tableName: 'gl_journal'
  })
  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
})