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 Admin SDK is initialized
if (!getApps().length) {
  initializeApp();
}

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

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

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

      if (!session) {
        res.status(401).send({ message: 'No session cookie' });
        return;
      }

      try {
        const decoded = await getAuth().verifySessionCookie(session, true);
        const role = decoded.role || 0;

        res.status(200).json({
          uid: decoded.uid,
          email: decoded.email,
          role,
        });
      } catch (err) {
        logger.warn('verifySession: Session invalid or expired', err);
        res.status(401).send({ message: 'Invalid session' });
      }
    });
  },
);
