"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.onCoupleLeave = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
/**
 * Firestore trigger that notifies the remaining partner when a user's coupleId
 * field is cleared (i.e. the user left the couple or was removed).
 *
 * Path: users/{userId}
 * Condition: previous coupleId was non-empty and new coupleId is null/missing.
 */
exports.onCoupleLeave = functions.firestore
    .document('users/{userId}')
    .onUpdate(async (change, context) => {
    var _a, _b, _c, _d, _e, _f;
    const { userId } = context.params;
    const previousData = (_a = change.before.data()) !== null && _a !== void 0 ? _a : {};
    const currentData = (_b = change.after.data()) !== null && _b !== void 0 ? _b : {};
    const previousCoupleId = previousData.coupleId;
    const currentCoupleId = currentData.coupleId;
    // Only act when coupleId transitions from a real value to null/empty.
    if (!previousCoupleId || typeof previousCoupleId !== 'string') {
        return;
    }
    if (currentCoupleId) {
        return;
    }
    const db = admin.firestore();
    const messaging = admin.messaging();
    const coupleDoc = await db.collection('couples').doc(previousCoupleId).get();
    if (!coupleDoc.exists) {
        console.warn(`[onCoupleLeave] couple ${previousCoupleId} not found`);
        return;
    }
    const userIds = ((_d = (_c = coupleDoc.data()) === null || _c === void 0 ? void 0 : _c.userIds) !== null && _d !== void 0 ? _d : []);
    const partnerId = userIds.find((uid) => uid !== userId);
    if (!partnerId) {
        console.warn(`[onCoupleLeave] no partner found for couple ${previousCoupleId}`);
        return;
    }
    // Make sure the partner is still paired in this couple.
    // If both users are leaving simultaneously, avoid duplicate/phantom notifications.
    const partnerUserDoc = await db.collection('users').doc(partnerId).get();
    const partnerCoupleId = (_e = partnerUserDoc.data()) === null || _e === void 0 ? void 0 : _e.coupleId;
    if (partnerCoupleId !== previousCoupleId) {
        console.log(`[onCoupleLeave] partner ${partnerId} is no longer in couple ${previousCoupleId}; skipping notification`);
        return;
    }
    const notificationPayload = {
        type: 'partner_left',
        title: 'Your partner has left',
        body: 'You are no longer paired. Tap to create a new invite.',
    };
    // Write an in-app notification record for the partner.
    // This is read-only denied for clients; the Cloud Function writes it.
    await db
        .collection('users')
        .doc(partnerId)
        .collection('notification_queue')
        .add(Object.assign(Object.assign({}, notificationPayload), { read: false, createdAt: admin.firestore.FieldValue.serverTimestamp() }));
    // Collect the partner's FCM tokens (legacy field + fcmTokens subcollection).
    const tokens = [];
    if (partnerUserDoc.exists) {
        const legacyToken = (_f = partnerUserDoc.data()) === null || _f === void 0 ? void 0 : _f.fcmToken;
        if (typeof legacyToken === 'string' && legacyToken.length > 0) {
            tokens.push(legacyToken);
        }
    }
    const tokenSnapshot = await db
        .collection('users')
        .doc(partnerId)
        .collection('fcmTokens')
        .get();
    tokenSnapshot.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) {
        console.log(`[onCoupleLeave] no FCM tokens for partner ${partnerId}`);
        return;
    }
    const fcmMessage = {
        token: tokens[0],
        notification: {
            title: notificationPayload.title,
            body: notificationPayload.body,
        },
        data: {
            type: notificationPayload.type,
        },
    };
    const sendResults = await Promise.allSettled(tokens.map((token) => messaging.send(Object.assign(Object.assign({}, fcmMessage), { token }))));
    const failures = [];
    sendResults.forEach((result, index) => {
        if (result.status === 'rejected') {
            failures.push(`${tokens[index]}: ${String(result.reason)}`);
        }
    });
    if (failures.length > 0) {
        console.error(`[onCoupleLeave] some notifications failed:`, failures);
    }
    console.log(`[onCoupleLeave] notified partner ${partnerId} that user ${userId} left couple ${previousCoupleId}`);
});
//# sourceMappingURL=onCoupleLeave.js.map