// packages/functions/src/shared/utils/internal/auth.ts

/**
 * @fileoverview Authentication utility functions
 * @description Functions for user authentication and authorization
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */

import { getFirebaseAdminAuth } from '@donotdev/firebase/server';

import type { NextApiRequest } from 'next';

// IMPORTANT: Don't call getAuth() at module load - breaks Firebase deployment
// const auth = getAuth(); // REMOVED - use getAuth() directly in functions instead

/**
 * Validates that user is authenticated
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */
export function assertAuthenticated(uid: string): string {
  if (!uid) {
    throw new Error('Authentication required');
  }
  return uid;
}

/**
 * Validates that user has admin privileges
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */
export async function assertAdmin(uid: string): Promise<string> {
  assertAuthenticated(uid);

  try {
    const user = await getFirebaseAdminAuth().getUser(uid); // Lazy initialization
    const isAdmin = user.customClaims?.isAdmin === true;

    if (!isAdmin) {
      throw new Error('Admin privileges required');
    }

    return uid;
  } catch (error) {
    throw new Error('Failed to verify admin status');
  }
}

/**
 * Verifies Firebase auth token from Vercel request
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */
export async function verifyFirebaseAuthToken(
  req: NextApiRequest
): Promise<string> {
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    throw new Error('Missing or invalid authorization header');
  }

  const token = authHeader.split('Bearer ')[1];

  if (!token) {
    throw new Error('Missing token in authorization header');
  }

  try {
    const decodedToken = await getFirebaseAdminAuth().verifyIdToken(token); // Lazy initialization
    return decodedToken.uid;
  } catch (error) {
    throw new Error('Invalid or expired token');
  }
}
