import { cookies } from "next/headers"
import { NextResponse } from "next/server"
import { platformUserFromToken } from "@/lib/auth/jwt-claims"
import { resolveServerOidcConfig } from "@/lib/auth/oidc-config"
import {
  SESSION_COOKIE_NAMES,
  applySessionCookies,
  computeExpiresAt,
  exchangeRefreshToken,
  isAccessTokenValid,
  isIdTokenJwtValid,
  resolveBearerToken,
} from "@/lib/auth/session"

export async function GET() {
  const jar = await cookies()
  const accessToken = jar.get(SESSION_COOKIE_NAMES.accessToken)?.value
  const refreshToken = jar.get(SESSION_COOKIE_NAMES.refreshToken)?.value
  const expiresAtRaw = jar.get(SESSION_COOKIE_NAMES.expiresAt)?.value

  if (!accessToken && !refreshToken) {
    return NextResponse.json({ authenticated: false })
  }

  if (isAccessTokenValid(accessToken, expiresAtRaw)) {
    const expiresAt = Number(expiresAtRaw)
    const user = platformUserFromToken(accessToken!)
    return NextResponse.json({
      authenticated: true,
      accessToken,
      refreshToken: refreshToken ?? null,
      expiresAt,
      user,
    })
  }

  if (!refreshToken) {
    return NextResponse.json({ authenticated: false, expired: true })
  }

  try {
    const cfg = await resolveServerOidcConfig()
    const tokens = await exchangeRefreshToken(refreshToken, cfg)

    let bearer: string
    try {
      bearer = resolveBearerToken(tokens)
    } catch {
      if (accessToken && isIdTokenJwtValid(accessToken)) {
        const expiresAt = Number(expiresAtRaw) || computeExpiresAt(3600)
        const user = platformUserFromToken(accessToken)
        return NextResponse.json({
          authenticated: true,
          accessToken,
          refreshToken: refreshToken ?? null,
          expiresAt,
          user,
        })
      }
      return NextResponse.json({ authenticated: false, expired: true })
    }

    const expiresAt = computeExpiresAt(tokens.expires_in ?? 3600)
    const user = platformUserFromToken(bearer)

    const response = NextResponse.json({
      authenticated: true,
      accessToken: bearer,
      refreshToken: tokens.refresh_token ?? refreshToken,
      expiresAt,
      user,
      refreshed: true,
    })
    applySessionCookies(response, tokens, bearer)
    return response
  } catch {
    return NextResponse.json({ authenticated: false, expired: true })
  }
}
