import { string } from 'alga-js'
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 token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  const resp: any = await fetchHelper(event, `models/m_product_category?$filter=${string.urlEncode('id neq '+body.productCategoryId)}&$orderby=${string.urlEncode('id asc')}`, 'GET', token, null)
  if(body.id && resp?.records?.[0]?.id) {
    const res: any = await fetchHelper(event, 'models/m_product/'+body.id, 'PUT', token, {
      M_Product_Category_ID: {
        id: resp.records[0].id,
        tableName: 'M_Product_Category_ID'
      },
      tableName: 'm_product'
    })
    if(res) {
      data = res
      data['status'] = 200
      data['message'] = ''
    }
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = {}

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    if(err.status >= 500 || err.statusCode >= 500) {
      data = {
        status: err.status || err.statusCode,
        message: err.detail || err.message || err.statusMessage
      }
    } else {
    try {
        let authToken: any = await refreshTokenHelper(event)
        data = await handleFunc(event, authToken)
      } catch(error: any) {
        data = {
          status: error.status || error.statusCode || 500,
          message: error.detail || error.message || error.statusMessage
        }
        forceLogoutHelper(event, data)
      }
    }
  }

  return data
})