import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import fetchHelper from "../../../utils/fetchHelper"
import strapiHelper from "../../../utils/strapiHelper"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  try {
    const response: any = await strapiHelper(event, 'm-products', 'POST', {
      data: {
        M_Product_ID: body.id,
        value: body.value,
        name: body.name
      }
    })
    if(response?.data) {
      data = response.data
    }
  } catch(err: any) {
    const response: any = await strapiHelper(event, 'm-products?filters[M_Product_ID]='+body.id, 'GET', null)
    if(response?.data?.[0]) {
      data = response.data[0]
    }
  }
  //@ts-ignore
  if(data?.documentId) {
    await fetchHelper(event, 'models/m_product/'+body.id, 'PUT', token, {
      //@ts-ignore
      Strapi_Product_ID: data.id,
      //@ts-ignore
      Strapi_Product_documentId: data.documentId
    })
  }

  return data
}

export default defineEventHandler(async (event) => {
  return await handleFunc(event)
})