"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.sendReengagementReminder = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
const THREE_DAYS_MS = 3 * 24 * 60 * 60 * 1000;
const TEN_DAYS_MS = 10 * 24 * 60 * 60 * 1000;
const REENGAGEMENT_COOLDOWN_MS = 3 * 24 * 60 * 60 * 1000;
/**
 * Re-engagement nudge for couples who went quiet.
 *
 * Schedule: 12:00 PM America/Chicago daily.
 *
 * Targets couples whose lastAnsweredAt is between 3 and 10 days ago —
 * recently lapsed but not completely inactive. Respects a 3-day cooldown
 * via reengagementSentAt to avoid spamming.
 *
 * Requires a Firestore composite index on couples: lastAnsweredAt ASC.
 */
exports.sendReengagementReminder = functions.pubsub
    .schedule('0 12 * * *')
    .timeZone('America/Chicago')
    .onRun(async () => {
    const db = admin.firestore();
    const messaging = admin.messaging();
    const now = Date.now();
    const threeDaysAgo = admin.firestore.Timestamp.fromMillis(now - THREE_DAYS_MS);
    const tenDaysAgo = admin.firestore.Timestamp.fromMillis(now - TEN_DAYS_MS);
    const snap = await db
        .collection('couples')
        .where('lastAnsweredAt', '>', tenDaysAgo)
        .where('lastAnsweredAt', '<', threeDaysAgo)
        .limit(200)
        .get();
    let notified = 0;
    let skipped = 0;
    await Promise.all(snap.docs.map(async (coupleDoc) => {
        var _a;
        const data = coupleDoc.data();
        const coupleId = coupleDoc.id;
        const userIds = ((_a = data.userIds) !== null && _a !== void 0 ? _a : []);
        if (userIds.length === 0) {
            skipped++;
            return;
        }
        // Respect cooldown — don't re-send within 3 days.
        const sentAt = data.reengagementSentAt;
        if (sentAt && now - sentAt.toMillis() < REENGAGEMENT_COOLDOWN_MS) {
            skipped++;
            return;
        }
        // Claim atomically so parallel runs don't double-send.
        const claimed = await db.runTransaction(async (tx) => {
            var _a;
            const fresh = await tx.get(coupleDoc.ref);
            const freshSentAt = (_a = fresh.data()) === null || _a === void 0 ? void 0 : _a.reengagementSentAt;
            if (freshSentAt && now - freshSentAt.toMillis() < REENGAGEMENT_COOLDOWN_MS)
                return false;
            tx.update(coupleDoc.ref, {
                reengagementSentAt: admin.firestore.FieldValue.serverTimestamp(),
            });
            return true;
        });
        if (!claimed) {
            skipped++;
            return;
        }
        await Promise.all(userIds.map((uid) => sendNudge(db, messaging, uid, coupleId)));
        notified += userIds.length;
    }));
    console.log(`[sendReengagementReminder] scanned ${snap.size}; notified ${notified}; skipped ${skipped}`);
});
async function sendNudge(db, messaging, userId, coupleId) {
    await db.collection('users').doc(userId).collection('notification_queue').add({
        type: 'reengagement',
        title: "It's been a while.",
        body: "Tonight's question is a good reason to reconnect.",
        read: false,
        createdAt: admin.firestore.FieldValue.serverTimestamp(),
    });
    const tokens = await getUserTokens(db, userId);
    if (tokens.length === 0)
        return;
    await Promise.allSettled(tokens.map((token) => messaging.send({
        token,
        notification: {
            title: "It's been a while.",
            body: "Tonight's question is a good reason to reconnect.",
        },
        data: {
            type: 'reengagement',
            couple_id: coupleId,
        },
    })));
}
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=reengagement.js.map