"use server"

import { getActionAccountContext } from "@/lib/server/get-account-context"
import {
  getActiveUserLeaderboardLast30DaysForRepo,
  getOptimizationCountsByRepo,
  getOptimizationsTimeSeriesData,
  getPullRequestEventTimeSeriesData,
  getRepositoryByIdForPayload,
} from "./queries"

/**
 * Server-side function to fetch all data needed for the repository detail page
 * in parallel. Eliminates the client-side auth→repo→stats waterfall.
 */
export async function getRepoDetailInitData(repositoryId: string, selectedPrYear?: number) {
  const accountContext = await getActionAccountContext()
  if (!accountContext) {
    return null
  }

  const { payload, userId } = accountContext

  const repository = await getRepositoryByIdForPayload(payload, repositoryId)
  if (!repository) {
    return { userId, repository: null, stats: null }
  }

  const prYear = selectedPrYear ?? new Date().getFullYear()

  // Fetch all statistics in parallel — these are all independent queries
  // Use the combined count query (single SQL) instead of two separate COUNT calls
  const [counts, optimizationsOverTime, successfulOptimizationsOverTime, prData, leaderboardData] =
    await Promise.all([
      getOptimizationCountsByRepo(repositoryId),
      getOptimizationsTimeSeriesData(repositoryId, false),
      getOptimizationsTimeSeriesData(repositoryId, true),
      getPullRequestEventTimeSeriesData(prYear, repositoryId),
      getActiveUserLeaderboardLast30DaysForRepo(repositoryId),
    ])

  const totalAttempts = counts.total
  const successfulAttempts = counts.successful

  // Process time series data
  let optimizationsTrend: number[] = []
  let optimizationsTrendDates: string[] = []
  if (Array.isArray(optimizationsOverTime) && optimizationsOverTime.length > 0) {
    optimizationsTrend = optimizationsOverTime.map(item => item?.count || 0)
    optimizationsTrendDates = optimizationsOverTime.map(item => item?.date || "")
  }

  let successfulOptimizationsTrend: number[] = []
  let successfulOptimizationsTrendDates: string[] = []
  if (
    Array.isArray(successfulOptimizationsOverTime) &&
    successfulOptimizationsOverTime.length > 0
  ) {
    successfulOptimizationsTrend = successfulOptimizationsOverTime.map(item => item?.count || 0)
    successfulOptimizationsTrendDates = successfulOptimizationsOverTime.map(
      item => item?.date || "",
    )
  }

  return {
    userId,
    orgId: "orgId" in payload ? payload.orgId : null,
    repository,
    stats: {
      totalAttempts: totalAttempts ?? 0,
      successfulAttempts: successfulAttempts ?? 0,
      optimizationsTrend,
      optimizationsTrendDates,
      successfulOptimizationsTrend,
      successfulOptimizationsTrendDates,
      prActivityData: Array.isArray(prData) ? prData : [],
      activeUsersData: Array.isArray(leaderboardData) ? leaderboardData : [],
      prYear,
    },
  }
}

export async function getRepoDetailPrActivityData(repositoryId: string, year: number) {
  const accountContext = await getActionAccountContext()
  if (!accountContext) {
    return null
  }

  const repository = await getRepositoryByIdForPayload(accountContext.payload, repositoryId)

  if (!repository) {
    return null
  }

  return getPullRequestEventTimeSeriesData(year, repositoryId)
}
