---
import { actions } from 'astro:actions'

import { stopImpersonating } from '../../lib/impersonation'
import { urlParamsToFormData } from '../../lib/urls'

// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const redirectUrl = Astro.url.searchParams.get('redirect') || Astro.request.headers.get('referer') || '/'

const stop = Astro.url.searchParams.get('stop')
if (stop) {
  await stopImpersonating(Astro)
  return Astro.redirect(redirectUrl)
}

const alreadyImpersonating = !!Astro.locals.actualUser
if (alreadyImpersonating) return Astro.redirect(redirectUrl)

const user = Astro.locals.user
if (!user?.admin) return Astro.rewrite('/404')

const impersonateResult = await Astro.callAction(
  actions.account.impersonate,
  urlParamsToFormData(Astro.url.searchParams)
)

if (!impersonateResult.error) {
  return Astro.redirect(impersonateResult.data.redirect)
}

return Astro.rewrite(`/500?message=${encodeURIComponent(impersonateResult.error.message)}`)
---
