// Your verifyHelper.ts (or wherever this function is)

import { getAuth } from 'firebase-admin/auth';
import type { Request } from 'express';
import * as cookie from 'cookie';
import { logger } from 'firebase-functions/v2'; // <--- Make sure you import logger here

export type DecodedAuthInfo = {
  uid: string;
  role: number;
};

export async function verifySessionFromRequest(
  req: Request,
): Promise<DecodedAuthInfo | null> {
  // --- ADD THESE LOGS ---
  logger.info('verifySessionFromRequest: STARTING verification');
  logger.info(
    'verifySessionFromRequest: Raw headers.cookie:',
    req.headers.cookie,
  ); // Log the raw cookie header
  // --- END ADDED LOGS ---

  const cookies = cookie.parse(req.headers.cookie || '');

  // --- ADD THESE LOGS ---
  logger.info('verifySessionFromRequest: Parsed cookies object:', cookies); // Log the parsed cookies object
  // --- END ADDED LOGS ---

  const session = cookies.__session;

  // --- ADD THESE LOGS ---
  logger.info(
    'verifySessionFromRequest: __session cookie value:',
    session ? 'Found (length: ' + session.length + ')' : 'Not Found',
  );
  // --- END ADDED LOGS ---

  if (!session) {
    logger.warn('verifySessionFromRequest: No __session cookie found.'); // Specific log for missing cookie
    return null;
  }

  try {
    const decoded = await getAuth().verifySessionCookie(session, true);
    const role = (decoded.role || 0) as number;
    logger.info(
      'verifySessionFromRequest: Session cookie decoded successfully for UID:',
      decoded.uid,
    ); // Log success
    return { uid: decoded.uid, role };
  } catch (err: unknown) {
    // Use 'any' type for err to easily access its properties
    logger.error(
      '[Auth] Session cookie verification failed:',
      err instanceof Error ? err.message : String(err),
    ); // Log the actual error message
    return null;
  }
}
