/**
 * Authentication Session Utilities
 *
 * Helper functions for creating and managing NextAuth sessions
 * Used by OTP verification to create proper sessions for dashboard access
 *
 * @module lib/auth-session
 */

import { prisma } from "./db";

/**
 * Create a session token for NextAuth
 *
 * This generates a session compatible with NextAuth's expectations
 * allowing OTP-verified users to access protected pages
 *
 * @param userId - User ID
 * @param email - User email
 * @returns Session token data
 */
export async function createAuthSession(userId: string, email: string) {
  // Create or update NextAuth session in database
  const sessionToken = generateSecureToken();
  const expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days

  try {
    // Note: NextAuth manages sessions differently
    // For OTP login, we'll return user data for client-side session
    return {
      user: {
        id: userId,
        email: email,
      },
      expires: expires.toISOString(),
      sessionToken,
    };
  } catch (error) {
    console.error("[AuthSession] Failed to create session:", error);
    throw new Error("Failed to create authentication session");
  }
}

/**
 * Generate secure random token
 */
function generateSecureToken(): string {
  const randomBytes = crypto.randomUUID();
  return Buffer.from(randomBytes).toString("base64url");
}
