import laravelHelper from "../../utils/laravelHelper";
import errorHandlingHelper from "../../utils/errorHandlingHelper";
import fetchHelper from "../../utils/fetchHelper";

// POST /api/ffn/selective-update-products
// body: { orderSourceId, jfskus: string[], fields: string[], dryRun?: boolean }
// Loads the Order Source (for jtl_merchantID / org / product price list version) and asks Laravel to
// push ONLY the selected fields of the selected JTL products to the matching iDempiere products.
// dryRun=true returns the exact per-product partial payload without writing anything.
export default defineEventHandler(async (event) => {
  try {
    const token = await getTokenHelper(event)
    const body = await readBody(event)
    if (!body?.orderSourceId) return { status: 400, success: false, message: 'orderSourceId is required' }
    if (!Array.isArray(body?.jfskus) || !body.jfskus.length) return { status: 400, success: false, message: 'Select at least one product' }
    if (!Array.isArray(body?.fields) || !body.fields.length) return { status: 400, success: false, message: 'Select at least one field' }

    const os: any = await fetchHelper(event, `models/c_ordersource/${body.orderSourceId}`, 'GET', token, null)
    if (!os) return { status: 404, success: false, message: 'Order Source not found' }

    const res: any = await laravelHelper(event, 'fulfiller/selective-update-products', 'POST', {
      orderSource: os,
      jfskus: body.jfskus,
      fields: body.fields,
      dryRun: body.dryRun === true,
    })
    return { status: 200, ...(res || {}) }
  } catch (err: any) {
    const data = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
    return { status: Number(data?.status || err?.status || 500), success: false, message: data?.message || err?.message || 'Selective update failed', error: err?.data ?? null }
  }
})
