import type { OAuthTokenResponse } from '~~/types/oauth'

export default eventHandler(async (event) => {
  const config = useRuntimeConfig()
  const session = await getUserSession(event)
  if (!session.jwt?.accessToken && !session.jwt?.refreshToken) {
    throw createError({
      statusCode: 401,
      message: 'Unauthorized'
    })
  }

  try {
    const { access_token, refresh_token } = await $fetch<OAuthTokenResponse>(
      `http://localhost:7080/realms/legalconsenthub/protocol/openid-connect/token`,
      {
        method: 'POST',
        headers: { 'content-type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          grant_type: 'refresh_token',
          client_id: config.oauth.keycloak.clientId,
          client_secret: config.oauth.keycloak.clientSecret,
          refresh_token: session.jwt.refreshToken
        }).toString()
      }
    )

    await setUserSession(event, {
      jwt: {
        accessToken: access_token,
        refreshToken: refresh_token || session.jwt.refreshToken
      },
      loggedInAt: Date.now()
    })

    return {
      accessToken: access_token,
      refreshToken: refresh_token || session.jwt.refreshToken
    }
  } catch {
    throw createError({
      statusCode: 401,
      message: 'refresh token is invalid'
    })
  }
})
