import { getServerSession } from "next-auth"
import { authOptions } from "@/lib/auth"

interface SessionUser {
  id: string
  email: string
  name?: string
  role: string
  orgId: string
  orgName: string
  orgSlug: string
}

/**
 * Get the current user from the session.
 * Returns null if not authenticated.
 */
export async function getUser(): Promise<SessionUser | null> {
  const session = await getServerSession(authOptions)
  if (!session?.user) return null
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return session.user as any as SessionUser
}

/**
 * Get the current org ID from the session.
 * Falls back to x-org-id header or first org for backwards compatibility.
 */
export async function getOrgId(headerOrgId?: string | null): Promise<string | null> {
  // 1. Try session first
  const user = await getUser()
  if (user?.orgId) return user.orgId

  // 2. Fall back to header (for API calls)
  if (headerOrgId) {
    const { resolveOrgId } = await import("@/lib/org")
    return resolveOrgId(headerOrgId)
  }

  // 3. Fall back to first org (single-tenant compat)
  const { resolveOrgId } = await import("@/lib/org")
  return resolveOrgId(null)
}
