// In your verifySession.ts (the API endpoint Cloud Function)
import { onRequest } from 'firebase-functions/v2/https';
import * as cookie from 'cookie';
import { getAuth } from 'firebase-admin/auth';
import { initializeApp, getApps } from 'firebase-admin/app';
import { corsMiddlewareHandler } from '../config';
import { logger } from 'firebase-functions/v2'; // Ensure logger is imported

if (!getApps().length) {
  initializeApp();
}

export const verifySession = onRequest(
  { region: 'asia-northeast3' },
  async (req, res) => {
    return corsMiddlewareHandler(req, res, async () => {
      logger.info('verifySession: Function invoked'); // This log is already there

      // --- ADD THESE LOGS ---
      logger.info(
        'verifySession (endpoint): Raw headers.cookie:',
        req.headers.cookie,
      );
      const cookies = cookie.parse(req.headers.cookie || '');
      logger.info('verifySession (endpoint): Parsed cookies object:', cookies);
      const session = cookies.__session;
      logger.info(
        'verifySession (endpoint): __session cookie value:',
        session ? 'Found' : 'Not Found',
      );
      // --- END ADDED LOGS ---

      if (req.method !== 'GET') {
        res.status(405).send('Method Not Allowed');
        return;
      }

      if (!session) {
        logger.warn(
          'verifySession (endpoint): No __session cookie found, returning 401.',
        ); // Specific warn
        res.status(401).send({ message: 'No session cookie' });
        return;
      }

      try {
        const decoded = await getAuth().verifySessionCookie(session, true);
        const role = decoded.role || 0;
        logger.info(
          'verifySession (endpoint): Session verified successfully for UID:',
          decoded.uid,
        ); // Log success

        res.status(200).json({
          uid: decoded.uid,
          email: decoded.email,
          role,
        });
      } catch (err: unknown) {
        // Use any for err to access message
        logger.warn(
          'verifySession (endpoint): Session invalid or expired, returning 401:',
          err instanceof Error ? err.message : String(err),
        ); // Specific warn
        res.status(401).send({ message: 'Invalid session' });
      }
    });
  },
);
