import { NextRequest, NextResponse } from "next/server"
import { connection } from "next/server"
import { getAllOptimizationEvents } from "@/app/(dashboard)/review-optimizations/action"
import { getActionAccountContext } from "@/lib/server/get-account-context"

export async function GET(request: NextRequest) {
  await connection()
  try {
    const accountContext = await getActionAccountContext()
    if (!accountContext) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    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 search = searchParams.get("search") || ""
    const repositoryId = searchParams.get("repositoryId") || undefined
    const status = searchParams.get("status") || "all"
    const eventType = searchParams.get("eventType") || "all"
    const reviewQuality = searchParams.get("reviewQuality") || "all"
    const sortBy = searchParams.get("sortBy") || "created_at_desc"

    // Build filter object
    const filter: Record<string, string | null | { not: null }> = {}
    if (repositoryId === "none") {
      filter.repository_id = null
    } else if (repositoryId) {
      filter.repository_id = repositoryId
    }
    if (status !== "all") {
      filter.status = status
    }
    if (eventType !== "all") {
      filter.event_type = eventType
    }
    if (reviewQuality !== "all") {
      filter.review_quality = reviewQuality
    }

    // Build sort object with allowlisted fields
    const ALLOWED_SORT_FIELDS = new Set([
      "created_at",
      "updated_at",
      "status",
      "event_type",
      "function_name",
      "repository_id",
    ])
    const [parsedField, parsedDirection] = sortBy.split("_").reduce(
      (acc, part, index, arr) => {
        if (index === arr.length - 1 && (part === "asc" || part === "desc")) {
          return [acc[0], part]
        }
        return [acc[0] ? `${acc[0]}_${part}` : part, acc[1]]
      },
      ["", "desc"] as [string, string],
    )
    const sortField = ALLOWED_SORT_FIELDS.has(parsedField) ? parsedField : "created_at"
    const sortDirection =
      parsedDirection === "asc" || parsedDirection === "desc" ? parsedDirection : "desc"
    const sort: Record<string, "asc" | "desc"> = {
      [sortField]: sortDirection,
    }

    const data = await getAllOptimizationEvents({
      payload: accountContext.payload,
      search: search || undefined,
      filter: Object.keys(filter).length > 0 ? filter : undefined,
      sort,
      page,
      pageSize,
    })

    return NextResponse.json(data, {
      headers: { "Cache-Control": "private, max-age=30, stale-while-revalidate=60" },
    })
  } catch (error) {
    console.error("Failed to fetch optimization events:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}
