"use server"

import { auth0 } from "@/lib/auth0"
import { redirect } from "next/navigation"
import { cache } from "react"
import { isTeamMemberCheck, isMembenchAllowed } from "@/lib/team-members"

const getCachedSession = cache(async () => {
  return auth0.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) {
    redirect("/login")
  }

  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) {
    redirect("/login")
  }

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

export const getAuthenticatedTeamSession = cache(async () => {
  const session = await getCachedSession()

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

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

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