"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.createDateMatchOnMutualLove = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
const LOVE = 'love';
/**
 * Creates a revealed date match when both partners have swiped LOVE on the
 * same date idea.
 *
 * Trigger: couples/{coupleId}/date_swipes/{dateIdeaId} (onWrite)
 *
 * The `date_matches` collection is server-write-only — Firestore rules deny all
 * client writes (`allow create, update, delete: if false`). This trigger is
 * therefore the single source of truth for match creation. The client only
 * records swipes and observes `date_matches` for the result.
 *
 * Idempotency: the match document id is the date idea id and creation runs in a
 * transaction, so repeated swipes on the same idea and concurrent invocations
 * never produce a duplicate match.
 */
exports.createDateMatchOnMutualLove = functions.firestore
    .document('couples/{coupleId}/date_swipes/{dateIdeaId}')
    .onWrite(async (change, context) => {
    var _a, _b, _c;
    const after = change.after.data();
    if (!after)
        return; // swipe document was deleted
    const actions = ((_a = after.actions) !== null && _a !== void 0 ? _a : {});
    const lovedBy = Object.entries(actions)
        .filter(([, entry]) => (entry === null || entry === void 0 ? void 0 : entry.action) === LOVE)
        .map(([uid]) => uid)
        .sort();
    // A match needs both partners to have loved the same idea.
    if (lovedBy.length < 2)
        return;
    const { coupleId, dateIdeaId } = context.params;
    const db = admin.firestore();
    const matchRef = db
        .collection('couples')
        .doc(coupleId)
        .collection('date_matches')
        .doc(dateIdeaId);
    await db.runTransaction(async (tx) => {
        const existing = await tx.get(matchRef);
        if (existing.exists)
            return;
        tx.set(matchRef, {
            dateIdeaId,
            matchedBy: lovedBy,
            revealedAt: admin.firestore.FieldValue.serverTimestamp(),
            fcmNotified: false,
        });
    });
    // Atomically claim FCM send so concurrent trigger 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) {
        const coupleDoc = await db.collection('couples').doc(coupleId).get();
        const userIds = ((_c = (_b = coupleDoc.data()) === null || _b === void 0 ? void 0 : _b.userIds) !== null && _c !== void 0 ? _c : []);
        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