const admin = require("firebase-admin");
const { onCall, HttpsError } = require("firebase-functions/v2/https");
const { onDocumentWritten } = require("firebase-functions/v2/firestore");

const { refsList } = require("..");

exports.userUpdateListener = onDocumentWritten(
  "users/{userID}",
  async (userSnap) => {
    try {
      const { userID } = userSnap.params;

      const currentData = userSnap?.data?.after?.data() || null;
      const previousData = userSnap?.data?.before?.data() || null;

      if (!currentData) {
        await admin.auth().deleteUser(userID);
      }

      if (!previousData) {
      } else if (!!previousData && !!currentData) {
        const { email = null } = currentData;

        try {
          if (previousData?.email && previousData?.email !== email && email) {
            await admin.auth().updateUser(userID, {
              email,
            });
          }
        } catch (e) {
          console.log(e);
        }
      }
    } catch (e) {
      console.log(e);
    }
  }
);

exports.deleteAccount = onCall(async ({ auth = {}, data = {} }) => {
  try {
    if (!auth.uid) {
      throw new HttpsError(
        "unauthenticated",
        "Vous devez être connecté pour effectuer cette action."
      );
    }

    const userDoc = await refsList.users.doc(auth.uid).get();

    if (!userDoc.exists) {
      throw new HttpsError("not-found", "L'utilisateur n'existe pas.");
    }

    await admin.auth().deleteUser(auth.uid);
    await userDoc.ref.delete();

    return { success: true };
  } catch (error) {
    console.error(error);
    throw new HttpsError(
      "internal",
      "Une erreur s'est produite lors de la suppression de votre compte."
    );
  }
});
