import { NextResponse } from "next/server"

import { auth } from "@/lib/auth"

export const runtime = "nodejs"

export async function GET(request: Request) {
  const result = await auth.api.getSession({ headers: request.headers, request, asResponse: true })

  if (!result) {
    return NextResponse.json({ user: null }, { status: 200 })
  }

  const body = await result.json()
  const response = NextResponse.json(body, {
    status: result.status,
  })

  const headersWithGetSetCookie = result.headers as Headers & { getSetCookie?: () => string[] | undefined }
  let setCookieHeaders =
    typeof headersWithGetSetCookie.getSetCookie === "function"
      ? headersWithGetSetCookie.getSetCookie() ?? []
      : []

  if (setCookieHeaders.length === 0) {
    const single = result.headers.get("set-cookie")
    if (single) {
      setCookieHeaders = [single]
    }
  }

  for (const cookie of setCookieHeaders) {
    response.headers.append("set-cookie", cookie)
  }

  return response
}
