"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.leaveCoupleCallable = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
/**
 * HTTPS callable that atomically unlinks a couple.
 *
 * The client cannot do this directly because Firestore rules prevent a user
 * from writing the partner's user document. The Admin SDK bypasses those rules.
 *
 * Steps:
 *  1. Verify the caller is a member of their current couple.
 *  2. Clear coupleId on both user docs (batch — atomic).
 *  3. Recursively delete the couple doc and all its subcollections.
 *
 * The existing onCoupleLeave Firestore trigger fires after step 2 and handles
 * partner notification, so we don't duplicate that here.
 */
exports.leaveCoupleCallable = functions.https.onCall(async (_data, context) => {
    var _a, _b;
    const callerId = (_a = context.auth) === null || _a === void 0 ? void 0 : _a.uid;
    if (!callerId) {
        throw new functions.https.HttpsError('unauthenticated', 'Must be signed in.');
    }
    if (!context.app) {
        throw new functions.https.HttpsError('failed-precondition', 'App Check verification required.');
    }
    const db = admin.firestore();
    const userDoc = await db.collection('users').doc(callerId).get();
    const coupleId = (_b = userDoc.data()) === null || _b === void 0 ? void 0 : _b.coupleId;
    if (!coupleId) {
        // Already unpaired — idempotent success.
        return { success: true };
    }
    const coupleRef = db.collection('couples').doc(coupleId);
    // Security review Batch 2: do the membership check, member-clearing, and couple-doc
    // delete in one transaction so two partners leaving concurrently can't clobber state.
    // Critically, only clear a member's coupleId if it STILL points at this couple — a
    // stale concurrent call must never wipe a coupleId set by a fresh re-pair.
    const result = await db.runTransaction(async (tx) => {
        var _a, _b, _c;
        const coupleSnap = await tx.get(coupleRef);
        if (!coupleSnap.exists) {
            const callerRef = db.collection('users').doc(callerId);
            const callerSnap = await tx.get(callerRef);
            if (((_a = callerSnap.data()) === null || _a === void 0 ? void 0 : _a.coupleId) === coupleId) {
                tx.update(callerRef, { coupleId: null });
            }
            return { membership: true };
        }
        const userIds = ((_c = (_b = coupleSnap.data()) === null || _b === void 0 ? void 0 : _b.userIds) !== null && _c !== void 0 ? _c : []);
        if (!userIds.includes(callerId)) {
            return { membership: false };
        }
        // Reads must precede writes in a transaction: snapshot every member first.
        const memberSnaps = await Promise.all(userIds.map((uid) => tx.get(db.collection('users').doc(uid))));
        memberSnaps.forEach((snap, i) => {
            var _a;
            if (((_a = snap.data()) === null || _a === void 0 ? void 0 : _a.coupleId) === coupleId) {
                tx.update(db.collection('users').doc(userIds[i]), { coupleId: null });
            }
        });
        tx.delete(coupleRef);
        return { membership: true };
    });
    if (!result.membership) {
        throw new functions.https.HttpsError('permission-denied', 'Not a member of this couple.');
    }
    // Couple doc is deleted in the transaction; sweep any subcollections left behind.
    // Idempotent if a concurrent caller already removed them.
    await db.recursiveDelete(coupleRef);
    console.log(`[leaveCoupleCallable] user ${callerId} left couple ${coupleId}`);
    return { success: true };
});
//# sourceMappingURL=leaveCoupleCallable.js.map