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

// POST /api/ffn/sync-bom-components
// body: { orderSourceId, jfskus: string[], dryRun?: boolean }
// Mirrors the JTL Stückliste structure of the selected BOM articles to iDempiere:
// PP_Product_BOM header + PP_Product_BOMLine per component (creates missing component products,
// updates a line's QtyBOM when JTL differs, sets IsBOM/isJtlBom on the master). BOM structure
// only — never touches master product fields. dryRun=true previews without writing.
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 BOM article' }

    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/sync-bom-components', 'POST', {
      orderSource: os,
      jfskus: body.jfskus,
      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 || 'BOM component sync failed', error: err?.data ?? null }
  }
})
