"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.onMessageWritten = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
/**
 * Firestore trigger that notifies the other partner when a chat message is
 * sent in a conversation (the couple chat or a per-question discussion).
 *
 * Path: couples/{coupleId}/conversations/{conversationId}/messages/{messageId}
 *
 * Respects the recipient's `notifChatMessage` preference (default: enabled).
 */
exports.onMessageWritten = functions.firestore
    .document('couples/{coupleId}/conversations/{conversationId}/messages/{messageId}')
    .onCreate(async (snap, context) => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const { coupleId, conversationId, messageId } = context.params;
    const db = admin.firestore();
    const messageData = snap.data();
    const authorId = typeof messageData.authorUserId === 'string' ? messageData.authorUserId : null;
    if (!authorId) {
        console.warn(`[onMessageWritten] no authorUserId on message ${messageId}`);
        return;
    }
    const coupleDoc = await db.collection('couples').doc(coupleId).get();
    if (!coupleDoc.exists) {
        console.warn(`[onMessageWritten] couple ${coupleId} not found`);
        return;
    }
    const userIds = ((_b = (_a = coupleDoc.data()) === null || _a === void 0 ? void 0 : _a.userIds) !== null && _b !== void 0 ? _b : []);
    const partnerId = userIds.find((uid) => uid !== authorId);
    if (!partnerId) {
        console.warn(`[onMessageWritten] no partner found for couple ${coupleId}`);
        return;
    }
    const partnerUserDoc = await db.collection('users').doc(partnerId).get();
    // Respect the partner's notification preference (opt-out; default is enabled).
    const notifEnabled = (_c = partnerUserDoc.data()) === null || _c === void 0 ? void 0 : _c.notifChatMessage;
    if (notifEnabled === false) {
        console.log(`[onMessageWritten] partner ${partnerId} has chat notifications off`);
        return;
    }
    const tokens = [];
    if (partnerUserDoc.exists) {
        const legacyToken = (_d = partnerUserDoc.data()) === null || _d === void 0 ? void 0 : _d.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(`[onMessageWritten] no FCM tokens for partner ${partnerId}`);
        return;
    }
    // The recipient sees the message from the author (their partner), so surface the author's
    // photo/name — the in-app chat bubble uses sender_avatar_url to show the partner's face.
    const authorDoc = await db.collection('users').doc(authorId).get();
    const authorPhotoUrl = (_f = (_e = authorDoc.data()) === null || _e === void 0 ? void 0 : _e.photoUrl) !== null && _f !== void 0 ? _f : '';
    const authorName = (_h = (_g = authorDoc.data()) === null || _g === void 0 ? void 0 : _g.displayName) !== null && _h !== void 0 ? _h : '';
    const payload = {
        notification: {
            title: authorName ? `${authorName} sent a message` : 'Your partner sent a message',
            body: 'Tap to read and reply.',
        },
        data: Object.assign({ type: 'chat_message', couple_id: coupleId, conversation_id: conversationId }, (authorPhotoUrl ? { sender_avatar_url: authorPhotoUrl } : {})),
    };
    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(`[onMessageWritten] some notifications failed:`, failures);
    }
    console.log(`[onMessageWritten] notified partner ${partnerId} for conversation ${conversationId} in couple ${coupleId}`);
});
//# sourceMappingURL=onMessageWritten.js.map