import { getAccountContext } from "@/lib/server/get-account-context"
import { getCachedInitialEvents, getCachedRepositories } from "./cached-data"
import { OptimizationsTable } from "./_components/OptimizationsTable"

export default async function ReviewOptimizationsPage() {
  const accountPayload = await getAccountContext()
  const accountKey = "orgId" in accountPayload ? accountPayload.orgId : accountPayload.userId

  const [initialData, availableRepositories] = await Promise.all([
    getCachedInitialEvents(accountKey, accountPayload),
    getCachedRepositories(accountKey, accountPayload),
  ])

  interface OptimizationEventSerialized {
    id: string
    function_name?: string
    file_path?: string
    repository?: { id: string; full_name?: string } | null
    speedup_x?: number
    speedup_pct?: number
    metadata?: Record<string, unknown> | null
    created_at: string
    status?: string
    event_type?: string
    trace_id: string
    review_quality: string
  }

  const initialEvents: OptimizationEventSerialized[] = (initialData?.events || []).map(
    (
      event: Record<string, unknown> & {
        repository?: { id: string; full_name?: string; name?: string } | null
      },
    ) =>
      ({
        ...event,
        created_at:
          event.created_at instanceof Date ? event.created_at.toISOString() : event.created_at,
        repository: event.repository
          ? {
              id: event.repository.id,
              full_name: event.repository.full_name || event.repository.name,
            }
          : null,
      }) as OptimizationEventSerialized,
  )

  return (
    <OptimizationsTable
      key={accountKey}
      initialEvents={initialEvents}
      initialTotalCount={initialData?.totalCount || 0}
      availableRepositories={availableRepositories}
    />
  )
}
