//NEEDS WORKS ON < PAST CODE >

import {
  onCall,
  HttpsError,
  CallableRequest,
} from 'firebase-functions/v2/https';
import { logger } from 'firebase-functions/v2';
import { allowedAdminEmails } from '../config';
import * as admin from 'firebase-admin';

interface DeleteUserData {
  uid: string;
}

export const deleteUserV2 = onCall(
  async (request: CallableRequest<DeleteUserData>) => {
    logger.info(`deleteUser: Function invoked by user: ${request.auth?.uid}`);

    // Ensure the function caller is authenticated (check request.auth)
    if (!request.auth) {
      logger.warn('deleteUser: Unauthenticated attempt.');
      throw new HttpsError( // Use imported HttpsError
        'unauthenticated',
        'User must be authenticated to delete accounts.',
      );
    }

    // Extract email from token (within request.auth)
    const callerEmail = request.auth.token.email || null;
    if (!callerEmail) {
      logger.error(
        `deleteUser: Email not found in token for UID: ${request.auth.uid}`,
      );
      throw new HttpsError( // Use imported HttpsError
        'invalid-argument',
        'Email not found in the authentication token.',
      );
    }
    logger.info(`deleteUser: Caller email: ${callerEmail}`);

    // Only allow certain emails to perform the delete action.
    // Trim whitespace from list for safety

    // Trim callerEmail for reliable comparison
    if (!allowedAdminEmails.includes(callerEmail.trim())) {
      logger.warn(
        `deleteUser: Permission denied for ${callerEmail}. Not in allowed list.`,
      );
      throw new HttpsError( // Use imported HttpsError
        'permission-denied',
        'Permission denied. This user is not allowed to delete accounts.',
      );
    }
    logger.info(`deleteUser: Permission granted for ${callerEmail}.`);

    // Get the user UID to be deleted from request.data
    // Type safety provided by CallableRequest<DeleteUserData>
    const userUidToDelete = request.data.uid;
    logger.info(`deleteUser: Attempting to delete UID: ${userUidToDelete}`);

    // Validate the UID from the client
    if (!userUidToDelete || typeof userUidToDelete !== 'string') {
      logger.error(
        'deleteUser: Invalid or missing UID in request data.',
        request.data,
      );
      throw new HttpsError( // Use imported HttpsError
        'invalid-argument',
        'The function must be called with a valid string UID of the user to delete.',
      );
    }

    try {
      logger.info(
        `deleteUser: Calling admin.auth().deleteUser for ${userUidToDelete}`,
      );
      await admin.auth().deleteUser(userUidToDelete);
      logger.info(`deleteUser: Successfully deleted user ${userUidToDelete}`);
      return { success: true };
    } catch (error) {
      logger.error(
        `deleteUser: Error deleting user ${userUidToDelete}:`,
        error,
      );
      // You could check error.code here for more specific errors like 'auth/user-not-found'
      throw new HttpsError('internal', 'Failed to delete the user.');
    }
  },
);
