"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.onUserDelete = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
/**
 * Auth deletion trigger — cascades account deletion server-side.
 *
 * Fires when a Firebase Auth user is deleted (via client deleteAccount() or
 * Admin SDK). The Admin SDK bypasses Firestore rules, so this function can
 * reach everything the client cannot.
 *
 * Steps (all best-effort after the auth account is already gone):
 *  1. If the user was in a couple:
 *     a. Clear the partner's coupleId.
 *     b. Send the partner an FCM push notification.
 *     c. Recursively delete the couple doc + all subcollections.
 *  2. Delete all Storage objects under users/{uid}/ (profile photo etc.).
 *  3. Recursively delete the user doc + all subcollections
 *     (entitlements, fcmTokens, notification_queue).
 */
exports.onUserDelete = functions.auth.user().onDelete(async (user) => {
    var _a, _b, _c, _d;
    const uid = user.uid;
    const db = admin.firestore();
    // ── 1. Couple unpair ──────────────────────────────────────────────────────
    const userDocRef = db.collection('users').doc(uid);
    const userDoc = await userDocRef.get();
    const coupleId = userDoc.exists
        ? (_a = userDoc.data()) === null || _a === void 0 ? void 0 : _a.coupleId
        : undefined;
    if (coupleId) {
        const coupleRef = db.collection('couples').doc(coupleId);
        const coupleDoc = await coupleRef.get();
        if (coupleDoc.exists) {
            const userIds = ((_c = (_b = coupleDoc.data()) === null || _b === void 0 ? void 0 : _b.userIds) !== null && _c !== void 0 ? _c : []);
            const partnerId = userIds.find((id) => id !== uid);
            if (partnerId) {
                const partnerRef = db.collection('users').doc(partnerId);
                const partnerDoc = await partnerRef.get();
                // Only act if the partner is still recorded in this couple.
                if (partnerDoc.exists && ((_d = partnerDoc.data()) === null || _d === void 0 ? void 0 : _d.coupleId) === coupleId) {
                    // Clear partner's coupleId first so the onCoupleLeave trigger does
                    // not fire a second time (it would find no partner left to notify).
                    await partnerRef.update({ coupleId: null });
                    // Send push notification to the partner.
                    await notifyPartner(partnerId, partnerDoc, db).catch((err) => {
                        console.warn(`[onUserDelete] FCM notification to partner ${partnerId} failed:`, err);
                    });
                }
            }
            // Recursively delete the couple doc + all subcollections.
            await db.recursiveDelete(coupleRef);
        }
    }
    // ── 2. Storage cleanup ────────────────────────────────────────────────────
    try {
        await admin.storage().bucket().deleteFiles({ prefix: `users/${uid}/` });
    }
    catch (err) {
        console.warn(`[onUserDelete] Storage cleanup failed for ${uid}:`, err);
    }
    // ── 3. User doc + subcollections ──────────────────────────────────────────
    await db.recursiveDelete(userDocRef);
    console.log(`[onUserDelete] completed cleanup for user ${uid}`);
});
async function notifyPartner(partnerId, partnerDoc, db) {
    var _a;
    const messaging = admin.messaging();
    // Collect FCM tokens (legacy field + fcmTokens subcollection).
    const tokens = [];
    const legacyToken = (_a = partnerDoc.data()) === null || _a === void 0 ? void 0 : _a.fcmToken;
    if (typeof legacyToken === 'string' && legacyToken.length > 0) {
        tokens.push(legacyToken);
    }
    const tokenSnap = await db.collection('users').doc(partnerId).collection('fcmTokens').get();
    tokenSnap.docs.forEach((doc) => {
        var _a;
        const t = (_a = doc.data()) === null || _a === void 0 ? void 0 : _a.token;
        if (typeof t === 'string' && t.length > 0 && !tokens.includes(t)) {
            tokens.push(t);
        }
    });
    if (tokens.length === 0)
        return;
    // Write an in-app notification record.
    await db
        .collection('users')
        .doc(partnerId)
        .collection('notification_queue')
        .add({
        type: 'partner_deleted_account',
        title: 'Your partner deleted their account',
        body: 'You are no longer paired. Tap to create a new invite.',
        read: false,
        createdAt: admin.firestore.FieldValue.serverTimestamp(),
    });
    const sendResults = await Promise.allSettled(tokens.map((token) => messaging.send({
        token,
        notification: {
            title: 'Your partner deleted their account',
            body: 'You are no longer paired. Tap to create a new invite.',
        },
        data: { type: 'partner_deleted_account' },
    })));
    sendResults.forEach((result, i) => {
        if (result.status === 'rejected') {
            console.warn(`[onUserDelete] FCM send to token ${tokens[i]} failed:`, result.reason);
        }
    });
}
//# sourceMappingURL=onUserDelete.js.map