"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.onAnswerWritten = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
/**
 * Firestore trigger that sends an FCM notification to the other partner when
 * one partner writes an answer under
 * couples/{coupleId}/daily_question/{date}/answers/{userId}.
 *
 * The notification payload is a data message so the client can route directly to
 * the answer reveal screen. It also contains a `notification` block for
 * system-tray display when the app is in the background.
 */
exports.onAnswerWritten = functions.firestore
    .document('couples/{coupleId}/daily_question/{date}/answers/{userId}')
    .onCreate(async (snap, context) => {
    var _a, _b, _c, _d, _e;
    const { coupleId, date, userId } = context.params;
    const db = admin.firestore();
    const coupleDoc = await db.collection('couples').doc(coupleId).get();
    if (!coupleDoc.exists) {
        console.warn(`[onAnswerWritten] couple ${coupleId} not found`);
        return;
    }
    const userIds = ((_b = (_a = coupleDoc.data()) === null || _a === void 0 ? void 0 : _a.userIds) !== null && _b !== void 0 ? _b : []);
    // Security review Batch 2: re-verify the writer actually belongs to this couple
    // before sending a cross-user notification. Firestore rules already enforce this,
    // but defense-in-depth ensures a stray/forged answer doc can't trigger a partner ping.
    if (!userIds.includes(userId)) {
        console.warn(`[onAnswerWritten] writer ${userId} is not a member of couple ${coupleId}`);
        return;
    }
    const partnerId = userIds.find((uid) => uid !== userId);
    if (!partnerId) {
        console.warn(`[onAnswerWritten] no partner found for couple ${coupleId}`);
        return;
    }
    // Look up the partner's FCM tokens. We support a legacy `fcmToken` field
    // on the user doc and a dedicated `fcmTokens` subcollection for multiple devices.
    const tokens = [];
    const partnerUserDoc = await db.collection('users').doc(partnerId).get();
    if (partnerUserDoc.exists) {
        const legacyToken = (_c = partnerUserDoc.data()) === null || _c === void 0 ? void 0 : _c.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(`[onAnswerWritten] no FCM tokens for partner ${partnerId}`);
        return;
    }
    // Respect the partner's notification preference (opt-out; default is enabled).
    const notifEnabled = (_d = partnerUserDoc.data()) === null || _d === void 0 ? void 0 : _d.notifPartnerAnswered;
    if (notifEnabled === false) {
        console.log(`[onAnswerWritten] partner ${partnerId} has partner-answered notifications off`);
        return;
    }
    const answerData = snap.data();
    const questionId = typeof answerData.questionId === 'string' ? answerData.questionId : '';
    // Sender (the partner who just answered) avatar — used as the notification large icon.
    const senderDoc = await db.collection('users').doc(userId).get();
    const senderAvatar = (_e = senderDoc.data()) === null || _e === void 0 ? void 0 : _e.photoUrl;
    const payload = {
        notification: {
            title: 'Your partner just answered!',
            body: "See what they shared for tonight's prompt.",
        },
        data: Object.assign({ type: 'partner_answered', couple_id: coupleId, question_id: questionId, date }, (typeof senderAvatar === 'string' && senderAvatar.length > 0
            ? { sender_avatar_url: senderAvatar }
            : {})),
    };
    const sendResults = await Promise.allSettled(tokens.map((token) => admin.messaging().send(Object.assign(Object.assign({}, payload), { token }))));
    const failures = [];
    sendResults.forEach((result, index) => {
        if (result.status === 'rejected') {
            failures.push(`${tokens[index]}: ${String(result.reason)}`);
        }
    });
    if (failures.length > 0) {
        console.error(`[onAnswerWritten] some notifications failed:`, failures);
    }
    // Track last activity time on the couple doc for re-engagement targeting.
    await db.collection('couples').doc(coupleId).update({
        lastAnsweredAt: admin.firestore.FieldValue.serverTimestamp(),
    }).catch((e) => console.warn('[onAnswerWritten] lastAnsweredAt update failed:', e));
    console.log(`[onAnswerWritten] notified partner ${partnerId} for couple ${coupleId} question ${questionId}`);
});
//# sourceMappingURL=onAnswerWritten.js.map