import { defineEventHandler, getHeader, parseCookies, sendRedirect } from 'h3'

export default defineEventHandler(async (event) => {
  const cookies = parseCookies(event)
  const keys = Object.keys(cookies)

  const key = keys.find(k => k.includes('better') && k.includes('session'))
    || keys.find(k => k.includes('session'))
  const token = key ? cookies[key] : ''

  const proto = getHeader(event, 'x-forwarded-proto') || 'https'
  const host = getHeader(event, 'host') || ''
  const base = `${proto}://${host}`
  const url = new URL('/app/return-from-magic-link', base)
  if (token) url.searchParams.set('token', token)

  await sendRedirect(event, url.toString(), 302)
})
