import { NextRequest, NextResponse } from "next/server"
import { connection } from "next/server"
import { auth0 } from "@/lib/auth0"
import { cookies } from "next/headers"
import { getUserOrganizations } from "@/components/dashboard/action"
import { getOptimizationPRs } from "@/app/(dashboard)/dashboard/action"
import type { AccountPayload } from "@codeflash-ai/common"

export async function GET(request: NextRequest) {
  await connection()
  try {
    const session = await auth0.getSession()
    if (!session?.user?.sub || !session?.user?.nickname) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    // Build AccountPayload from session + org cookie (same as getAccountContext)
    const cookieStore = await cookies()
    const orgId = cookieStore.get("currentOrganizationId")?.value

    let payload: AccountPayload
    if (orgId) {
      const result = await getUserOrganizations(session.user.sub)
      if (result.success && result.organizations?.some(org => org.id === orgId)) {
        payload = { orgId }
      } else {
        payload = { userId: session.user.sub, username: session.user.nickname }
      }
    } else {
      payload = { userId: session.user.sub, username: session.user.nickname }
    }

    const { searchParams } = request.nextUrl
    const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10) || 1)
    const pageSize = Math.min(
      100,
      Math.max(1, parseInt(searchParams.get("pageSize") || "10", 10) || 10),
    )
    const eventTypeFilter = searchParams.get("eventTypeFilter") || "all"
    const repositoryId = searchParams.get("repositoryId") || undefined

    const data = await getOptimizationPRs(payload, page, pageSize, eventTypeFilter, repositoryId)
    return NextResponse.json(data, {
      headers: { "Cache-Control": "private, max-age=30, stale-while-revalidate=60" },
    })
  } catch (error) {
    console.error("Failed to fetch optimization PRs:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}
