"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.notifyOnDateMatch = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
/**
 * Fires the "It's a match!" notification when a date match is created.
 *
 * Trigger: couples/{coupleId}/date_matches/{dateIdeaId} (onCreate)
 *
 * Date swipes are E2E-encrypted, so the server can no longer detect mutual love.
 * Mutual-match detection now happens client-side (whichever partner records the
 * second LOVE writes the match marker, validated by Firestore rules). This trigger
 * only sends the push to both partners — it never reads swipe content.
 *
 * Idempotency: `fcmNotified` is claimed in a transaction so concurrent invocations
 * (or a client retry) never double-send. The match doc id is the date idea id, so
 * the marker itself is already de-duplicated by the client transaction + rules.
 */
exports.notifyOnDateMatch = functions.firestore
    .document('couples/{coupleId}/date_matches/{dateIdeaId}')
    .onCreate(async (snap, context) => {
    var _a, _b;
    if (!snap.exists)
        return;
    const { coupleId, dateIdeaId } = context.params;
    const db = admin.firestore();
    const matchRef = snap.ref;
    // Atomically claim the FCM send so concurrent invocations don't double-send.
    const shouldSend = await db.runTransaction(async (tx) => {
        var _a;
        const doc = await tx.get(matchRef);
        if (!doc.exists || ((_a = doc.data()) === null || _a === void 0 ? void 0 : _a.fcmNotified) === true)
            return false;
        tx.update(matchRef, { fcmNotified: true });
        return true;
    });
    if (!shouldSend)
        return;
    const coupleDoc = await db.collection('couples').doc(coupleId).get();
    const userIds = ((_b = (_a = coupleDoc.data()) === null || _a === void 0 ? void 0 : _a.userIds) !== null && _b !== void 0 ? _b : []);
    await Promise.all(userIds.map((uid) => notifyDateMatch(db, uid, coupleId, dateIdeaId)));
});
async function notifyDateMatch(db, userId, coupleId, dateIdeaId) {
    await db.collection('users').doc(userId).collection('notification_queue').add({
        type: 'date_match',
        title: "It's a match!",
        body: "You both want to go on this date. Time to make it happen.",
        read: false,
        createdAt: admin.firestore.FieldValue.serverTimestamp(),
    });
    const tokens = await getUserTokens(db, userId);
    if (tokens.length === 0)
        return;
    await Promise.allSettled(tokens.map((token) => admin.messaging().send({
        token,
        notification: {
            title: "It's a match!",
            body: "You both want to go on this date. Time to make it happen.",
        },
        data: {
            type: 'date_match',
            couple_id: coupleId,
            date_idea_id: dateIdeaId,
        },
    })));
}
async function getUserTokens(db, userId) {
    var _a;
    const tokens = [];
    const userDoc = await db.collection('users').doc(userId).get();
    const legacy = (_a = userDoc.data()) === null || _a === void 0 ? void 0 : _a.fcmToken;
    if (typeof legacy === 'string' && legacy.length > 0)
        tokens.push(legacy);
    const snap = await db.collection('users').doc(userId).collection('fcmTokens').get();
    snap.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);
    });
    return tokens;
}
//# sourceMappingURL=createDateMatch.js.map