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(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(resData?.['id']) {
    newObjValue = {...newObjValue, 
      M_RMA_ID: {
        id: resData.id,
        tableName: 'M_RMA'
      }
    }
  }
  if(body.inOutLines) {
    newObjValue = {...newObjValue, 
      M_InOutLine: body.inOutLines.map((item: any) => {
        const rmaLine = resData.m_rmaline.filter((i: any) => i.line === item.line)
        if(rmaLine?.[0]?.id) {
          item['M_RMALine_ID'] = {
            id: rmaLine[0].id
          }
        }
        return item
      })
    }
  }
  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,
    'doc-action': 'CO',
    ...newObjValue,
    tableName: 'M_Inout'
  })
  if(res) {
    data['customer_return'] = res
  }

  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_rma/'+body.id, 'PUT', token, {
    M_InOut_ID: {
      id: resData['customer_return'].id
    },
    //'doc-action': 'CO'
  })

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

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?.inOutId) {
    newObjValue = {...newObjValue, 
      InOut_ID: {
        id: body.inOutId,
        tableName: 'M_InOut'
      }
    }
  }
  if(body.orderId) {
    newObjValue = {...newObjValue, 
      C_Order_ID: {
        id: body.orderId,
        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(body.salesRepId) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: body.salesRepId,
        tableName: 'AD_User'
      }
    }
  }
  //if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        identifier: 'EUR',
        tableName: 'C_Currency'
      }
    }
  //}
  if(body.partnerId) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: body.partnerId,
        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: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.IsActive,
    //processing: body.processing,
    //documentNo: body.documentNo,
    name: body.name,
    //processed: body.processed,
    //isApproved: body.isApproved,
    //amt: body.amt,
    isSOTrx: true,
    description: body.description,
    help: body.help ?? '',
    M_RMAType_ID: {
      id: body.rmaTypeId,
      tableName: 'M_RMAType'
    },
    'doc-action': 'CO',
    ...newObjValue,
    tableName: 'm_rma'
  })
  if(res?.id) {
    data['customer_rma'] = res

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

    const returnData: any = await handleReturnFunc(event, authToken, body, res2)
    const rmaData: any = {} //await handleRMAFunc(event, authToken, res2, returnData)
    
    if(returnData?.['customer_return']) {
      data['status'] = 200
      data['message'] = ''

      data = {...data, ...rmaData, ...returnData}
    } else {
      data['status'] = 500
      data['message'] = 'Customer Return is not being created'
    }
  }

  return data
}

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
})