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

// Deletes DRAFT productions only (lines first, then the header)
const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)
  const ids: any[] = body?.ids || []

  const errors: string[] = []
  for(const id of ids) {
    try {
      const production: any = await fetchHelper(event, `models/m_production/${id}`, 'GET', token, null)
      if(!production?.id) {
        errors.push(`Production ${id} not found`)
        continue
      }
      if(production.Processed === true || !['DR', 'IN', 'IP'].includes(production.DocStatus?.id)) {
        errors.push(`${production.DocumentNo || id}: only draft productions can be deleted`)
        continue
      }

      const linesRes: any = await fetchHelper(event, `models/m_productionline?$filter=${encodeURIComponent(`M_Production_ID eq ${id}`)}&$top=500`, 'GET', token, null)
      for(const line of (linesRes?.records || [])) {
        await fetchHelper(event, `models/m_productionline/${line.id}`, 'DELETE', token, null)
      }
      await fetchHelper(event, `models/m_production/${id}`, 'DELETE', token, null)
    } catch(err: any) {
      errors.push(`${id}: ${err?.data?.detail || err?.data?.message || err?.message || 'delete failed'}`)
    }
  }

  data = {
    status: errors.length > 0 ? 422 : 200,
    message: errors.join('; ')
  }
  return data
}

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

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch(error) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})
