import { NextRequest } from 'next/server'
import { getSessionUser } from '@/lib/auth'
import { readSession, setSessionCookie } from '@/lib/auth/session'
import { sameSiteRedirect } from '@/lib/app-url'
import { contextDashboard } from '@/lib/domain/modes'
import { switchContext } from '@/lib/data/modes'

/** Open one mode by key and land in its dashboard — used when there is only one. */
export async function GET(req: NextRequest) {
  const user = await getSessionUser()
  if (!user) return sameSiteRedirect('/login')
  const key = req.nextUrl.searchParams.get('key') ?? ''
  const session = await readSession()
  if (!session || !key) return sameSiteRedirect('/dashboard')
  const r = await switchContext({ id: user.id, email: user.email, name: user.name, role: user.role }, key, { id: user.id, label: user.name || user.email })
  if (!r.ok) return sameSiteRedirect('/dashboard')
  await setSessionCookie({ ...session, ctx: key, preview: null })
  return sameSiteRedirect(contextDashboard(r.context))
}
