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

const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)
  const documentNo = String(body?.documentNo ?? body?.search ?? '').trim()

  if (!documentNo) {
    throw createError({ statusCode: 400, statusMessage: 'DocumentNo is required' })
  }

  // Escape single quotes in the document number for the OData literal.
  const safeDoc = documentNo.replace(/'/g, "''")
  const filter = `DocumentNo eq '${safeDoc}'`
  const expand = `M_RMALine($expand=M_Product_ID)`

  const res: any = await fetchHelper(
    event,
    `models/m_rma?$filter=${string.urlEncode(filter)}&$expand=${string.urlEncode(expand)}&$top=5`,
    'GET',
    token,
    null
  )

  if (!res?.records || res.records.length === 0) {
    return { found: false }
  }

  const rma = res.records[0]
  const lines = Array.isArray(rma.M_RMALine) ? rma.M_RMALine : []

  return {
    found: true,
    rma: {
      id: rma.id,
      documentNo: rma.DocumentNo,
      name: rma.Name,
      description: rma.Description,
      organizationId: rma.AD_Org_ID?.id ?? null,
      organization: rma.AD_Org_ID?.identifier ?? null,
      docStatus: rma.DocStatus?.id ?? rma.DocStatus ?? null,
      partnerId: rma.C_BPartner_ID?.id ?? null,
      partnerName: rma.C_BPartner_ID?.identifier ?? null,
      rmaTypeId: rma.M_RMAType_ID?.id ?? null,
      rmaType: rma.M_RMAType_ID?.identifier ?? null,
      inOutId: rma.InOut_ID?.id ?? null,
      inOut: rma.InOut_ID?.identifier ?? null
    },
    lines: lines.map((l: any) => {
      const p = l.M_Product_ID || {}
      return {
        rmaLineId: l.id,
        line: l.Line,
        qty: Number(l.Qty ?? 0),
        product: {
          id: p.id,
          Name: p.Name,
          Value: p.Value,
          SKU: p.SKU,
          UPC: p.UPC,
          MPN: p.mpn ?? null,
          ASIN: p.asin ?? null,
          AD_Org_ID: p.AD_Org_ID ?? null,
          Strapi_Product_documentId: p.Strapi_Product_documentId ?? null,
          C_UOM_ID: p.C_UOM_ID ?? null
        }
      }
    })
  }
}

export default defineEventHandler(async (event) => {
  // Auth-only retry: a business 404 no longer triggers a token refresh.
  return await withAuthRetry(event, handleFunc)
})
