import {getApps, initializeApp} from "firebase-admin/app";
import {getAuth} from "firebase-admin/auth";
import * as logger from "firebase-functions/logger";
import {onDocumentDeleted} from "firebase-functions/v2/firestore";

const adminApp = getApps().length > 0 ? getApps()[0] : initializeApp();

export const deleteUserAuthOnUserDocumentDeleted = onDocumentDeleted(
  "users/{uid}",
  async (event) => {
    const uid = event.params.uid;

    if (!uid) {
      logger.error("Missing uid in users/{uid} delete trigger.");
      return;
    }

    try {
      await getAuth(adminApp).deleteUser(uid);
      logger.info(
        "Deleted auth user after Firestore user deletion.",
        {uid}
      );
    } catch (error) {
      logger.error(
        "Failed to delete auth user after Firestore user deletion.",
        {
          uid,
          error,
        }
      );
      throw error;
    }
  }
);
