import { onRequest } from 'firebase-functions/v2/https';
import { logger } from 'firebase-functions/v2';
import {
  getFirestore,
  CollectionReference,
  Query,
} from 'firebase-admin/firestore';
import { initializeApp, getApps } from 'firebase-admin/app';
import type { DocumentData } from 'firebase-admin/firestore';

import { corsMiddlewareHandler, ALLOWED_COLLECTIONS } from '../config';
import {
  verifySessionFromRequest,
  buildQueryWithAccessControl,
} from '../utils';
import type { BoardAccessMode } from '../types/boardItem';

if (!getApps().length) initializeApp();
const db = getFirestore();

export const countBoards = onRequest(
  { region: 'asia-northeast3' },
  async (request, response) => {
    return corsMiddlewareHandler(request, response, async () => {
      logger.info('countBoards: CORS‑enabled function called');

      /* 1. method guard ---------------------------------------------------- */
      if (request.method !== 'POST') {
        response.status(405).send({ message: 'Method Not Allowed' });
        return;
      }

      /* 2. optional auth --------------------------------------------------- */
      let userRole = 0;
      let userId: string | null = null;

      const authUser = await verifySessionFromRequest(request);
      if (authUser) {
        userId = authUser.uid;
        userRole = authUser.role;
      }

      /* 3. body params & validation --------------------------------------- */
      const { collection = '', access = 'public' } = request.body as Partial<{
        collection: string;
        access: string;
      }>;

      // collection allow‑list
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      if (!ALLOWED_COLLECTIONS.has(collection as any)) {
        response.status(400).send({ message: 'Invalid collection' });
        return;
      }

      // access string check
      if (!['public', 'private', 'admin'].includes(access)) {
        response.status(400).send({ message: 'Bad access mode' });
        return;
      }

      const accessParam: BoardAccessMode = access as BoardAccessMode;
      const effectiveAccess: BoardAccessMode = userId ? accessParam : 'public';

      logger.info(
        `countBoards: uid=${userId ?? 'anon'}, role=${userRole}, ` +
          `requested=${accessParam}, effective=${effectiveAccess}`,
      );

      /* 4. build filtered query ------------------------------------------- */
      let q: Query<DocumentData>;
      try {
        q = buildQueryWithAccessControl(
          db.collection(collection) as CollectionReference<DocumentData>,
          effectiveAccess,
          userId,
          userRole,
        );
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
      } catch (err: any) {
        response
          .status(err?.message?.includes('Unauthorized') ? 401 : 403)
          .send({
            message: err instanceof Error ? err.message : 'Access denied',
          });
        return;
      }

      /* 5. run count() ----------------------------------------------------- */
      try {
        const aggSnap = await q.count().get();
        const count =
          typeof aggSnap.data().count === 'number' ? aggSnap.data().count : 0;
        response.status(200).send({ count });
      } catch (err) {
        logger.error('countBoards: Firestore error', err);
        response.status(500).send({ message: 'Internal Server Error' });
      }
    });
  },
);
