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),
  ])

  const initialEvents = (initialData?.events || []).map((event: any) => ({
    ...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,
  }))

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