import {onCall, HttpsError} from "firebase-functions/v2/https";
import * as admin from "firebase-admin";
import {Logger} from "../core/logger/logger";

export const deleteUserAccount = onCall(
    async (request) => {
      if (request == null) {
        throw new HttpsError("failed-precondition", "The function must be called while authenticated");
      }
      if (!request.auth) {
        throw new HttpsError("unauthenticated", "You must be authenticated to delete your account");
      }
      const uid = request.auth.uid;
      const logger = new Logger("deleteUserAccount");
      const db = admin.firestore();
      try {
        // 1. Delete user from Firebase Auth first — if this fails, data is still recoverable
        await admin.auth().deleteUser(uid);
        // 2. Delete Firestore data (user doc + subcollections: devices, notifications)
        const userRef = db.collection("users").doc(uid);
        await db.recursiveDelete(userRef);
        // 3. Delete subscription document
        const subRef = db.collection("subscriptions").doc(uid);
        await subRef.delete();
        logger.info(`User ${uid} deleted successfully`);
      } catch (e) {
        logger.error(`Error deleteUserAccount users/${uid}: ${e}`);
        throw new HttpsError("internal", "Error deleting user account");
      }
    });
