import fetchHelper from '../../utils/fetchHelper'

// Dedicated, stateless token refresh for the app (NEW). The app sends the refresh_token it stored
// at login (cross-origin, header/body based — no cookies). We call iDempiere's `auth/refresh`
// exactly like refreshTokenHelper does, but sourced from the request body instead of cookies, and
// return only the new { token, refresh_token }. No cookies set, no existing route touched.
export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const refreshToken = body?.refresh_token

  if (!refreshToken) {
    setResponseStatus(event, 400)
    return { error: 'refresh_token required' }
  }

  try {
    // Empty token arg → fetchHelper sends no Authorization header; the refresh_token authenticates.
    const resToken: any = await fetchHelper(event, 'auth/refresh', 'POST', '', {
      refresh_token: refreshToken,
      clientId: body?.clientId,
      userId: body?.userId,
    })

    if (resToken?.token) {
      return { token: resToken.token, refresh_token: resToken.refresh_token ?? refreshToken }
    }
    setResponseStatus(event, 401)
    return { error: 'refresh failed' }
  } catch {
    setResponseStatus(event, 401)
    return { error: 'refresh failed' }
  }
})
