import { string } from 'alga-js'
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)
  const id = getRouterParam(event, 'id')

  const response: any = await strapiHelper(event, `ad-attachments?filters[AD_Table_ID][$eq]=259&filters[Record_ID][$eq]=${id}`, 'GET', null)
  if(response?.data?.[0]?.id) {
    data['Strapi_Attachment_documentId'] = response.data[0].id
    data['status'] = 200
    data['message'] = ''
  } else {
    const resp: any = await strapiHelper(event, `ad-attachments`, 'POST', {
      data: {
        AD_Table_ID: 259,
        Record_ID: id,
        Record_UU: body.uid
      }
    })
    if(resp) {
      data['Strapi_Attachment_documentId'] = resp.data.id
      data['status'] = 200
      data['message'] = ''
    }
  }

  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: any) {
      data = {
        status: error.status || error.statusCode || 500,
        message: error.detail || error.message || error.statusMessage
      }
      //if(data.status < 500) {
        //@ts-ignore
        //setCookie(event, 'user', null)
      //}
    }
  }

  return data
})