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"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  const query = getQuery(event)
  const organizationId = query?.org ?? getCookie(event, 'organizationId')
  const email = query?.email ?? ''

  const filter = `(isActive eq true OR isActive eq false) AND AD_Org_ID eq ${organizationId} AND EMail eq '${email}'`
  const res: any = await fetchHelper(event, `models/c_bpartner?$filter=${string.urlEncode(filter)}&$orderby=${string.urlEncode('c_bpartner_id desc')}`, 'GET', token, null)
  if(Number(res?.records?.length ?? 0) >= 1) {
    data = res.records[0]

    const res2: any = await fetchHelper(event, `models/c_bpartner_location?$filter=c_bpartner_id eq ${res.records[0].id}&$expand=c_location_id`, 'GET', token, null)
    if(Number(res2?.records?.length ?? 0) >= 1) {
      data['ship_address'] = res2.records.filter((i: any) => i.IsShipTo)?.[0]?.C_Location_ID ?? res2.records[0]?.C_Location_ID ?? {}
      data['ship_partnerlocation_id'] = res2.records.filter((i: any) => i.IsShipTo)?.[0]?.id ?? res2.records[0]?.id ?? ''
      data['bill_address'] = res2.records.filter((i: any) => i.IsBillTo)?.[0]?.C_Location_ID ?? res2.records[0]?.C_Location_ID ?? {}
      data['bill_partnerlocation_id'] = res2.records.filter((i: any) => i.IsBillTo)?.[0]?.id ?? res2.records[0]?.id ?? ''
    }

    const res3: any = await fetchHelper(event, `models/ad_user?$filter=${string.urlEncode(filter)}&$orderby=${string.urlEncode('ad_user_id desc')}`, 'GET', token, null)
    if(Number(res3?.records?.length ?? 0) >= 1) {
      data['ship_user_id'] = res3.records.filter((i: any) => i.IsShipTo)?.[0]?.id ?? res3.records[0]?.id ?? ''
      data['bill_user_id'] = res3.records.filter((i: any) => i.IsBillTo)?.[0]?.id ?? res3.records[0]?.id ?? ''
    }
  }

  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 = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})