import { NextResponse } from "next/server"
import { cookies } from "next/headers"
import { getSessionUser } from "@/lib/session"
import { getAccountContext } from "@/lib/account"
import { getAdapter, saveEsignConnection, type ESignProvider } from "@/lib/esign"
import { verifyState, ESIGN_NONCE_COOKIE } from "@/lib/esign/state"

// OAuth callback — exchanges the code for tokens and stores the connection.
export async function GET(request: Request, { params }: { params: Promise<{ provider: string }> }) {
  const { provider } = await params
  const adapter = getAdapter(provider)
  const settings = new URL("/settings/integrations", request.url)

  const cookieStore = await cookies()
  const nonceCookie = cookieStore.get(ESIGN_NONCE_COOKIE)?.value
  const done = (p: Record<string, string>) => {
    for (const [k, v] of Object.entries(p)) settings.searchParams.set(k, v)
    const res = NextResponse.redirect(settings)
    res.cookies.set(ESIGN_NONCE_COOKIE, "", { path: "/", maxAge: 0 })
    return res
  }

  const url = new URL(request.url)
  const code = url.searchParams.get("code")
  const state = url.searchParams.get("state")
  const oauthError = url.searchParams.get("error")

  if (oauthError || !adapter || adapter.kind !== "oauth") return done({ error: "connect_failed" })

  const st = state ? verifyState(state) : null
  // CSRF: state nonce must match the cookie, and the session must be the same owner.
  if (!code || !st || st.provider !== provider || !nonceCookie || nonceCookie !== st.nonce) {
    return done({ error: "invalid_state" })
  }
  const user = await getSessionUser()
  if (!user) return done({ error: "invalid_state" })
  const ctx = await getAccountContext(user.id)
  if (ctx.ownerId !== st.ownerId) return done({ error: "invalid_state" })

  try {
    const tokens = await adapter.exchangeCode(code)
    if (!tokens.accountId || !tokens.baseUri) throw new Error("No account returned from provider")
    await saveEsignConnection(st.ownerId, provider as ESignProvider, tokens)
    return done({ connected: provider })
  } catch {
    return done({ error: "connect_failed" })
  }
}
