import { onRequest } from 'firebase-functions/v2/https';
import { getAuth } from 'firebase-admin/auth';
import { initializeApp, getApps } from 'firebase-admin/app';
import * as cookie from 'cookie';
import { logger } from 'firebase-functions/v2';
import { cookieExpiration, corsMiddlewareHandler } from '../config';
// ✅ Admin SDK init
if (!getApps().length) {
  initializeApp(); // ✅ auto uses service account in Firebase Functions
}

export const createSession = onRequest(
  { region: 'asia-northeast3' },
  async (req, res) => {
    return corsMiddlewareHandler(req, res, async () => {
      logger.info('countBoards: CORS‑enabled function called');
      if (req.method !== 'POST') {
        res.status(405).send('Method not allowed');
        return;
      }

      const idToken = req.body?.idToken;

      if (!idToken) {
        res.status(400).send('Missing ID token');
        return;
      }

      const auth = getAuth();
      try {
        const expiresIn = cookieExpiration;
        const sessionCookie = await auth.createSessionCookie(idToken, {
          expiresIn,
        });

        // Set cookie
        const options = {
          httpOnly: true,
          secure: true,
          maxAge: expiresIn / 1000,
          sameSite: 'lax' as const,
          path: '/',
        };

        res.setHeader(
          'Set-Cookie',
          cookie.serialize('__session', sessionCookie, options),
        );
        res.status(200).json({ success: true });
      } catch (error) {
        res.status(401).send('Invalid token');
      }
    });
  },
);
