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 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.warehouseId) {
    newObjValue = {...newObjValue, M_Warehouse_ID: {
      id: body.warehouseId,
      tableName: 'M_Warehouse'
    }}
  }
  if(body.warehouseToId) {
    newObjValue = {...newObjValue, M_WarehouseTo_ID: {
      id: body.warehouseToId,
      tableName: 'M_Warehouse'
    }}
  }
  if(body.shipperId) {
    newObjValue = {...newObjValue, M_Shipper_ID: {
      id: body.shipperId,
      tableName: 'M_Shipper'
    }}
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, SalesRep_ID: {
      id: body.salesRepId,
      tableName: 'AD_User'
    }}
  }
  if(body.userId) {
    newObjValue = {...newObjValue, AD_User_ID: {
      id: body.userId,
      tableName: 'AD_User'
    }}
  }
  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.docTypeId) {
    newObjValue = {...newObjValue, C_DocType_ID: {
      id: body.docTypeId,
      tableName: 'C_DocType'
    }}
  }
  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.freightCostRuleId) {
    newObjValue = {...newObjValue, FreightCostRule: {
      id: body.freightCostRuleId
    }}
  }
  if(body.priorityRuleId) {
    newObjValue = {...newObjValue, PriorityRule: {
      id: body.priorityRuleId
    }}
  }
  if(body.deliveryRuleId) {
    newObjValue = {...newObjValue, DeliveryRule: {
      id: body.deliveryRuleId
    }}
  }
  if(body.deliveryViaRuleId) {
    newObjValue = {...newObjValue, DeliveryViaRule: {
      id: body.deliveryViaRuleId
    }}
  }
  if(body.docStatusId) {
    newObjValue = {...newObjValue, DocStatus: {
      id: body.docStatusId
    }}
  }
  if(body.movementLines) {
    newObjValue = {...newObjValue, m_movementline: body.movementLines}
  }

  // Reconditioning: link the customer return (m_inout, MovementType C+) the moved
  // stock came from. Needs the custom column M_Movement.M_Customer_Return_ID
  // (Search → M_InOut). Until it exists iDempiere rejects the unknown column, so
  // the create is retried once WITHOUT the link — the movement itself must never fail.
  const customerReturnId = Number(body.customerReturnId) > 0 ? Number(body.customerReturnId) : null

  const buildPayload = (withReturnLink: boolean) => ({
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    documentNo: body.documentNo,
    movementDate: body.movementDate,
    approvalAmt: body.approvalAmt,
    chargeAmt: body.chargeAmt,
    freightAmt: body.freightAmt,
    isApproved: body.isApproved,
    isInTransit: body.isInTransit,
    description: body.description,
    POReference: body.poReference,
    processed: body.processed,
    processing: body.processing,
    /*DocStatus: {
      id: 'CO'
    },*/
    ...newObjValue,
    ...(withReturnLink && customerReturnId ? { M_Customer_Return_ID: { id: customerReturnId, tableName: 'M_InOut' } } : {}),
    tableName: 'm_movement'
  })

  let res: any = null
  let customerReturnLinked = false
  if(customerReturnId) {
    try {
      res = await fetchHelper(event, 'models/m_movement', 'POST', token, buildPayload(true))
      customerReturnLinked = true
    } catch(linkErr: any) {
      const msg = String(linkErr?.data?.detail || linkErr?.data?.message || linkErr?.message || '')
      // Only swallow the "unknown column" case — auth errors must still bubble to the refresh wrapper.
      if(Number(linkErr?.status ?? linkErr?.statusCode) === 401) throw linkErr
      console.warn('[stock-transfers/store] M_Customer_Return_ID not accepted, creating movement without the link:', msg)
      res = await fetchHelper(event, 'models/m_movement', 'POST', token, buildPayload(false))
    }
  } else {
    res = await fetchHelper(event, 'models/m_movement', 'POST', token, buildPayload(false))
  }
  if(res) {
    data = res
    data['status'] = 200
    data['message'] = ''
    data['customerReturnLinked'] = customerReturnLinked
  }

  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) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})