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"
import { resolveDefaultInOutDocTypeId, docTypeFkPatch } from "../../utils/inoutDocType"

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

  if(!body.docTypeId) {
    // BACKSTOP: this m_inout is always a customer return (linked M_RMA_ID) —
    // without C_DocType_ID iDempiere rejects it ("FillMandatory - Document
    // Type"). Fail-soft: unresolved → nothing merged → same error as before.
    newObjValue = {...newObjValue, ...docTypeFkPatch(await resolveDefaultInOutDocTypeId(event, 'MCR', token))}
  }

  try {
    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
    }
  } catch(error: any) {
    console.error('M_InOut creation error:', error)
    throw new Error(`Customer Return creation failed: ${error.message || error.statusMessage || 'Unknown error'}`)
  }

  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.rmaDocTypeId) {
    newObjValue = {...newObjValue,
      C_DocType_ID: {
        id: body.rmaDocTypeId,
        tableName: 'C_DocType'
      }
    }
  } else {
    newObjValue = {...newObjValue,
      C_DocType_ID: {
        id: '1000031',
        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
      })
    }
  }

  // Check for existing orphaned RMA (completed RMA without a customer return M_InOut)
  // This can happen when a previous attempt created the RMA but failed to create the M_InOut
  let existingRma: any = null
  if(body?.inOutId) {
    try {
      const existingRmaRes: any = await fetchHelper(event, `models/m_rma?$filter=${encodeURIComponent(`InOut_ID eq ${body.inOutId} AND DocStatus eq 'CO'`)}&$expand=m_rmaline&$orderby=${encodeURIComponent('m_rma_id desc')}`, 'GET', token, null)
      if(existingRmaRes?.records?.length > 0) {
        // Check if there's already a customer return M_InOut linked to this RMA
        const rmaId = existingRmaRes.records[0].id
        const existingReturnRes: any = await fetchHelper(event, `models/m_inout?$filter=${encodeURIComponent(`M_RMA_ID eq ${rmaId} AND DocStatus eq 'CO'`)}`, 'GET', token, null)
        if(!existingReturnRes?.records?.length) {
          // Orphaned RMA found - reuse it instead of creating a new one
          existingRma = existingRmaRes.records[0]
          console.log('Found orphaned RMA (no customer return M_InOut):', rmaId)
        }
      }
    } catch(e) {
      console.warn('Could not check for existing RMAs:', e)
    }
  }

  let rmaData2: any = null
  if(existingRma) {
    // Reuse the existing orphaned RMA
    data['customer_rma'] = existingRma
    rmaData2 = existingRma
  } else {
    // Create new RMA
    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)
      rmaData2 = res2
    }
  }

  if(rmaData2?.id) {
    const returnData: any = await handleReturnFunc(event, authToken, body, rmaData2)
    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
})