"use server"

import { getSession, Session } from "@auth0/nextjs-auth0"
import { cache } from "react"
import { isTeamMemberCheck } from "@/lib/team-members"

const getCachedSession = cache(async (): Promise<Session | null | undefined> => {
  return getSession()
})

export async function getUserId(): Promise<string | null> {
  const session = await getCachedSession()
  return session?.user?.sub || null
}

export async function getUserIdAndUsername(): Promise<{ username: string; userId: string }> {
  const session = await getCachedSession()

  if (!session?.user?.sub || !session?.user?.nickname) {
    throw new Error("User session not found or incomplete")
  }

  return {
    userId: session.user.sub,
    username: session.user.nickname,
  }
}

export async function isTeamMember(): Promise<boolean> {
  const session = await getCachedSession()
  if (!session?.user) {
    return false
  }
  return isTeamMemberCheck(session.user)
}

export async function requireTeamMember(): Promise<void> {
  const session = await getCachedSession()

  if (!session?.user) {
    throw new Error("Authentication required")
  }

  if (!isTeamMemberCheck(session.user)) {
    throw new Error("Access denied: Team member access required")
  }
}

export const getAuthenticatedTeamSession = cache(async (): Promise<Session | null> => {
  const session = await getCachedSession()

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

  return isTeamMemberCheck(session.user) ? session : null
})
