import { cache } from "react"
import { cookies } from "next/headers"
import { redirect } from "next/navigation"
import { auth0 } from "@/lib/auth0"
import { getUserOrganizations } from "@/components/dashboard/action"
import type { AccountPayload } from "@codeflash-ai/common"

export interface SessionAccountContext {
  payload: AccountPayload
  userId: string
  username: string
}

async function resolveAccountPayload(userId: string, username: string): Promise<AccountPayload> {
  const cookieStore = await cookies()
  const orgId = cookieStore.get("currentOrganizationId")?.value

  if (orgId) {
    // Validate user is a member of this org
    const result = await getUserOrganizations(userId)
    if (result.success && result.organizations?.some(org => org.id === orgId)) {
      return { orgId }
    }
    // Invalid org cookie — fall through to personal mode
  }

  return { userId, username }
}

/**
 * Server-side utility to determine the current account context (personal or org).
 * Reads the auth session + org cookie to build an AccountPayload for data fetching.
 * Cached per request via React `cache()`.
 */
export const getAccountContext = cache(async (): Promise<AccountPayload> => {
  const session = await auth0.getSession()

  if (!session?.user?.sub || !session?.user?.nickname) {
    redirect("/login")
  }

  return resolveAccountPayload(session.user.sub, session.user.nickname)
})

/**
 * Server-action-safe variant that returns the validated account payload plus
 * the authenticated user identity, or null when there is no active session.
 */
export async function getActionAccountContext(): Promise<SessionAccountContext | null> {
  const session = await auth0.getSession()

  if (!session?.user?.sub || !session?.user?.nickname) {
    return null
  }

  const userId = session.user.sub
  const username = session.user.nickname

  return {
    payload: await resolveAccountPayload(userId, username),
    userId,
    username,
  }
}

export const getSessionAccountContext = cache(async (): Promise<SessionAccountContext> => {
  const session = await auth0.getSession()

  if (!session?.user?.sub || !session?.user?.nickname) {
    redirect("/login")
  }

  const userId = session.user.sub
  const username = session.user.nickname

  return {
    payload: await resolveAccountPayload(userId, username),
    userId,
    username,
  }
})
