//NEEDS WORKS ON < PAST CODE >

import { onRequest } from 'firebase-functions/v2/https';
import { logger } from 'firebase-functions/v2';
// Import Request/Response from express

// Import the MIDDLEWARE HANDLER and db from config
import { corsMiddlewareHandler, db } from '../config'; // Use the middleware export name
// Import error utility
import { toErrorWithMessage } from '../utils';

export const checkEmailDuplicateV2 = onRequest(async (request, response) => {
  return corsMiddlewareHandler(request, response, async () => {
    logger.info('checkEmailDuplicate: Function invoked via CORS Middleware.');

    if (request.method !== 'POST') {
      logger.warn(`checkEmailDuplicate: Method not allowed: ${request.method}`);
      response.status(405).send({ message: 'Method Not Allowed.' });
      return;
    }

    const { email } = request.body;
    // ... rest of your validation and try/catch logic using db and logger ...
    logger.info(`checkEmailDuplicate: Checking email: ${email}`);

    if (!email || typeof email !== 'string') {
      logger.warn('checkEmailDuplicate: Missing or invalid email field.');
      response.status(400).send({
        /* ... */
      });
      return;
    }

    try {
      const usersCollection = db.collection('users');
      const querySnapshot = await usersCollection
        .where('email', '==', email)
        .limit(1)
        .get();

      if (!querySnapshot.empty) {
        logger.info(`checkEmailDuplicate: Email ${email} exists.`);
        response.send({ status: 'exists' });
      } else {
        logger.info(`checkEmailDuplicate: Email ${email} is available.`);
        response.send({ status: 'available' });
      }
    } catch (error: unknown) {
      const errorMsg = toErrorWithMessage(error).message;
      logger.error(
        `checkEmailDuplicate: Error checking email ${email}: ${errorMsg}`,
        { error },
      );
      response.status(500).send({
        /* ... */
      });
    }
  }); // End of corsMiddlewareHandler callback
}); // End of onRequest
