import { enhanceSession } from '../../utils/auth'
import { resolveSession } from '../../utils/session-resolver'
import { createSuccessResponse } from '../../utils/errors'
import { useDB, eq } from '../../utils/database'
import { user as userTable } from '../../database/schema/auth'

/**
 * Get user session with impersonation and ban checking.
 * This endpoint enhances Better Auth's session with custom logic.
 * Returns null session for anonymous users (no 401 error).
 *
 * If Better Auth's cache returns stale user data, we refresh it directly from the database.
 */
export default defineEventHandler(async (event) => {
  const session = await resolveSession(event)

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

  // Check if user data needs to be refreshed from database
  // Better Auth's cookie cache (5 minutes) might return stale user data
  // We refresh user data directly from the database to ensure it's up-to-date
  const db = useDB()
  const [freshUser] = await db
    .select({
      name: userTable.name,
      image: userTable.image
    })
    .from(userTable)
    .where(eq(userTable.id, session.user.id))
    .limit(1)

  // If we got fresh user data, update the session with it
  // Only update fields that are part of the AuthUser type
  if (freshUser) {
    session.user = {
      ...session.user,
      name: freshUser.name,
      image: freshUser.image ?? undefined
    }
  }

  // Enhance session with impersonation and ban checking
  // This may throw 403 if user is banned
  const enhancedSession = await enhanceSession(session, event)
  return createSuccessResponse(enhancedSession)
})
