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

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

  let newObjValue = {}
  if(resData?.id) {
    newObjValue = {...newObjValue, 
      InOut_ID: {
        id: resData.id,
        tableName: 'M_InOut'
      }
    }
  }
  if(resData.C_Order_ID?.id) {
    newObjValue = {...newObjValue,
      C_Order_ID: {
        id: resData.C_Order_ID.id,
        tableName: 'C_Order'
      }
    }
  }
  if(body.docTypeId) {
    newObjValue = {...newObjValue, 
      C_DocType_ID: {
        identifier: 'Customer Return Material',
        tableName: 'C_DocType'
      }
    }
  }
  //if(body.docStatusId) {
    newObjValue = {...newObjValue, 
      DocStatus: {
        id: 'IP'
      }
    }
  //}
  if(resData.SalesRep_ID?.id) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: resData.SalesRep_ID.id,
        tableName: 'AD_User'
      }
    }
  }
  //if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        identifier: 'EUR',
        tableName: 'C_Currency'
      }
    }
  //}
  if(resData.C_BPartner_ID?.id) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: resData.C_BPartner_ID.id,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.rmaLines) {
    newObjValue = {...newObjValue, 
      M_RMALine: body.rmaLines.map((i: any) => {
        delete i.id
        return i
      })
    }
  }

  const res: any = await fetchHelper(event, 'models/m_rma', 'POST', token, {
    AD_Org_ID: {
      id: resData.AD_Org_ID.id,
      tableName: 'AD_Org'
    },
    isActive: resData.IsActive,
    //processing: body.processing,
    //documentNo: body.documentNo,
    name: body.name,
    //processed: body.processed,
    //isApproved: body.isApproved,
    //amt: body.amt,
    isSOTrx: true,
    description: resData.Description,
    help: resData.Help,
    M_RMAType_ID: {
      id: body.rmaTypeId,
      tableName: 'M_RMAType'
    },
    ...newObjValue,
    tableName: 'm_rma'
  })
  if(res) {
    data['customer_rma'] = res

    const res2: any = await fetchHelper(event, `models/m_rma/${res.id}?$expand=m_rmaline`, 'GET', token, null)
    if(res2?.m_rmaline) {
      data['customer_rma_lines'] = res2?.m_rmaline
    }
  }

  return data
}

/*const handleRMAFunc = async (event: any, authToken: any = null, body: any = null, resData: any = null) => {
  let data: any = {}
  //const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)

  const res: any = await fetchHelper(event, 'models/m_inout/'+body.id, 'PUT', token, {
    M_RMA_ID: {
      uid: resData['customer_rma'].uid
    },
   //'doc-action': 'CO'
  })

  const res2: any = await fetchHelper(event, `models/m_inoutline?$filter=${string.urlEncode('M_InOut_ID eq '+body.id)}`, 'GET', token, null)
  if(res2) {
    for(let customerInOutLine of (res2?.records || [])) {
      const rmaLine = data['customer_rma_lines'].filter((item: any) => item.line === customerInOutLine.line)
      if(customerInOutLine && rmaLine?.[0]) {
        await fetchHelper(event, 'models/m_inoutline/'+customerInOutLine.id, 'PUT', token, {
          M_RMALine_ID: {
            id: rmaLine[0].id
          }
        })
      }
    }
    data['inoutline2'] = res2
    data['rmaline2'] = data['customer_rma_lines']
  }

  if(res) {
    data['inout2'] = res
  }
  
  return data
}*/

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

  let newObjValue = {}
  if(body.movementTypeId) {
    newObjValue = {...newObjValue, 
      MovementType: {
        id: body.movementTypeId,
      }
    }
  }
  if(body.docTypeId) {
    newObjValue = {...newObjValue, 
      C_DocType_ID: {
        id: body.docTypeId,
        tableName: 'C_DocType'
      }
    }
  }
  if(body.partnerId) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: body.partnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.partnerLocationId) {
    newObjValue = {...newObjValue, 
      C_BPartner_Location_ID: {
        id: body.partnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.userId) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: body.userId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.dropShipPartnerId) {
    newObjValue = {...newObjValue, 
      DropShip_BPartner_ID: {
        id: body.dropShipPartnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.dropShipPartnerLocationId) {
    newObjValue = {...newObjValue, 
      DropShip_Location_ID: {
        id: body.dropShipPartnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.dropShipUserId) {
    newObjValue = {...newObjValue, 
      DropShip_User_ID: {
        id: body.dropShipUserId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.returnPartnerId) {
    newObjValue = {...newObjValue, 
      Return_BPartner_ID: {
        id: body.returnPartnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.returnPartnerLocationId) {
    newObjValue = {...newObjValue, 
      Return_Location_ID: {
        id: body.returnPartnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.returnUserId) {
    newObjValue = {...newObjValue, 
      Return_User_ID: {
        id: body.returnUserId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.warehouseId) {
    newObjValue = {...newObjValue, 
      M_Warehouse_ID: {
        id: body.warehouseId,
        tableName: 'M_Warehouse'
      }
    }
  }
  if(body.deliveryRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryRule: {
        id: body.deliveryRuleId
      }
    }
  }
  if(body.freightCostRuleId) {
    newObjValue = {...newObjValue, 
      FreightCostRule: {
        id: body.freightCostRuleId
      }
    }
  }
  if(body.deliveryViaRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryViaRule: {
        id: body.deliveryViaRuleId
      }
    }
  }
  if(body.priorityRuleId) {
    newObjValue = {...newObjValue, 
      PriorityRule: {
        id: body.priorityRuleId
      }
    }
  }
  if(body.orderId) {
    newObjValue = {...newObjValue,
      C_Order_ID: {
        id: body.orderId,
        tableName: 'C_Order'
      }
    }
  }
  if(body.docStatusId) {
    newObjValue = {...newObjValue, 
      DocStatus: {
        id: body.docStatusId
      }
    }
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: body.salesRepId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.projectId) {
    newObjValue = {...newObjValue, 
      C_Project_ID: {
        id: body.projectId,
        tableName: 'C_Project'
      }
    }
  }
  if(body.campaignId) {
    newObjValue = {...newObjValue, 
      C_Campaign_ID: {
        id: body.campaignId,
        tableName: 'C_Campaign'
      }
    }
  }
  if(body.inOutLines) {
    newObjValue = {...newObjValue, 
      M_InOutLine: body.inOutLines
    }
  }
  if(new Boolean(body.isCommissionedConfirmed)) {
    newObjValue = {...newObjValue, IsCommissionedConfirmed: body.isCommissionedConfirmed}
  }

  const res: any = await fetchHelper(event, 'models/m_inout', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    documentNo: body.documentNo,
    description: body.description,
    movementDate: body.movementDate,
    processed: body.processed,
    isSOTrx: body.isSOTrx,
    isPrinted: body.isPrinted,
    dateAcct: body.dateAcct,
    POReference: body.poReference,
    freightAmt: body.freightAmt,
    chargeAmt: body.chargeAmt,
    dateOrdered: body.dateOrdered,
    sendEMail: body.sendEMail,
    noPackages: body.noPackages,
    isInTransit: body.isInTransit,
    isApproved: body.isApproved,
    isInDispute: body.isInDispute,
    volume: body.volume,
    weight: body.weight,
    isDropShip: body.isDropShip,
    processedOn: body.processedOn,
    isAlternateReturnAddress: body.isAlternateReturnAddress,
    M_RMA_ID: {
      uid: '1d4d6f17-48fe-4487-8376-da674fd940c3'
    },
    ...newObjValue,
    tableName: 'M_Inout'
  })
  if(res) {
    data['customer_return'] = res

    const returnData = await handleReturnFunc(event, authToken, body, res)
    const rmaData = {} //await handleRMAFunc(event, authToken, res, returnData)
    
    data['status'] = 200
    data['message'] = ''

    data = {...data, ...rmaData, ...returnData}
  }

  return data
}

//@ts-ignore
export default defineEventHandler(async (event: any) => {
  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) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})