"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.sendGentleReminderCallable = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
const GENTLE_REMINDER_MAX_PER_HOUR = 5;
const GENTLE_REMINDER_WINDOW_MS = 60 * 60 * 1000; // 1 hour
/**
 * Sends a gentle nudge from one partner to the other when the caller has
 * already answered today's question but the partner hasn't.
 *
 * Rate limits:
 *  - Per-user: max 5 gentle reminders per rolling hour. Guarded by a server-side
 *    transaction on `rate_limits/{uid}_gentle_reminder` so malicious clients
 *    cannot bypass it by calling the callable in a loop. The Android-side
 *    NotificationRateLimiter remains for UX but is not the authoritative guard.
 *  - Per-couple: one reminder per couple per calendar day (UTC). The lock is
 *    stored in couples/{coupleId}/gentle_reminders/{date} so it survives
 *    function restarts and is visible to both partners.
 *
 * The notification is both an FCM push (for the system tray) and an entry in
 * the partner's notification_queue (for in-app display).
 */
exports.sendGentleReminderCallable = functions.https.onCall(async (_data, context) => {
    var _a, _b, _c, _d, _e;
    const callerId = (_a = context.auth) === null || _a === void 0 ? void 0 : _a.uid;
    if (!callerId) {
        throw new functions.https.HttpsError('unauthenticated', 'Must be signed in.');
    }
    if (!context.app) {
        throw new functions.https.HttpsError('failed-precondition', 'App Check verification required.');
    }
    const db = admin.firestore();
    // ── 1. Resolve couple + partner ──────────────────────────────────────────
    const userDoc = await db.collection('users').doc(callerId).get();
    const coupleId = (_b = userDoc.data()) === null || _b === void 0 ? void 0 : _b.coupleId;
    if (!coupleId) {
        throw new functions.https.HttpsError('failed-precondition', 'Not in a couple.');
    }
    const coupleDoc = await db.collection('couples').doc(coupleId).get();
    if (!coupleDoc.exists) {
        throw new functions.https.HttpsError('not-found', 'Couple not found.');
    }
    const userIds = ((_d = (_c = coupleDoc.data()) === null || _c === void 0 ? void 0 : _c.userIds) !== null && _d !== void 0 ? _d : []);
    const partnerId = userIds.find((id) => id !== callerId);
    if (!partnerId) {
        throw new functions.https.HttpsError('failed-precondition', 'No partner found.');
    }
    // ── 2. Server-side per-user throttle: 5 per hour (rolling window) ────────
    const now = admin.firestore.Timestamp.now();
    const rateLimitRef = db.collection('rate_limits').doc(`${callerId}_gentle_reminder`);
    const throttleResult = await db.runTransaction(async (tx) => {
        const snap = await tx.get(rateLimitRef);
        const data = snap.data();
        let windowStart;
        let count;
        if (!snap.exists || !data) {
            windowStart = now;
            count = 0;
        }
        else {
            windowStart = data.windowStart;
            count = (typeof data.count === 'number' ? data.count : 0);
            const elapsedMs = now.toMillis() - windowStart.toMillis();
            if (elapsedMs >= GENTLE_REMINDER_WINDOW_MS) {
                // Rolling window has expired; start a fresh one.
                windowStart = now;
                count = 0;
            }
        }
        if (count >= GENTLE_REMINDER_MAX_PER_HOUR) {
            const retryAfterMs = GENTLE_REMINDER_WINDOW_MS - (now.toMillis() - windowStart.toMillis());
            const retryAfterMinutes = Math.max(1, Math.ceil(retryAfterMs / 60000));
            return { allowed: false, retryAfterMinutes };
        }
        tx.set(rateLimitRef, {
            count: count + 1,
            windowStart,
            updatedAt: now,
        }, { merge: true });
        return { allowed: true, count: count + 1, windowStart };
    });
    if (!throttleResult.allowed) {
        throw new functions.https.HttpsError('resource-exhausted', `Too many gentle reminders. Try again in ${throttleResult.retryAfterMinutes} minutes.`);
    }
    // ── 3. Rate limit: one per couple per day ────────────────────────────────
    const today = new Date().toISOString().slice(0, 10); // e.g. "2026-06-19"
    const lockRef = db
        .collection('couples')
        .doc(coupleId)
        .collection('gentle_reminders')
        .doc(today);
    const existingLock = await lockRef.get();
    if (existingLock.exists) {
        return { sent: false, reason: 'already_sent_today' };
    }
    // ── 4. Collect partner FCM tokens ────────────────────────────────────────
    const tokens = [];
    const partnerDoc = await db.collection('users').doc(partnerId).get();
    if (partnerDoc.exists) {
        const legacyToken = (_e = partnerDoc.data()) === null || _e === void 0 ? void 0 : _e.fcmToken;
        if (typeof legacyToken === 'string' && legacyToken.length > 0) {
            tokens.push(legacyToken);
        }
    }
    const tokenSnap = await db
        .collection('users')
        .doc(partnerId)
        .collection('fcmTokens')
        .get();
    tokenSnap.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);
        }
    });
    // ── 5. Write in-app notification record ──────────────────────────────────
    await db
        .collection('users')
        .doc(partnerId)
        .collection('notification_queue')
        .add({
        type: 'gentle_reminder',
        title: 'Your partner is thinking about you.',
        body: "They left tonight's question open. Answer when you're ready.",
        read: false,
        sent: false,
        createdAt: admin.firestore.FieldValue.serverTimestamp(),
    });
    // ── 6. Claim the daily rate-limit lock ───────────────────────────────────
    await lockRef.set({
        sentBy: callerId,
        sentAt: admin.firestore.FieldValue.serverTimestamp(),
    });
    // ── 7. Send FCM push ─────────────────────────────────────────────────────
    if (tokens.length > 0) {
        const sendResults = await Promise.allSettled(tokens.map((token) => admin.messaging().send({
            token,
            notification: {
                title: 'Your partner is thinking about you.',
                body: "They left tonight's question open. Answer when you're ready.",
            },
            data: {
                type: 'gentle_reminder',
                couple_id: coupleId,
            },
        })));
        sendResults.forEach((result, i) => {
            if (result.status === 'rejected') {
                console.warn(`[sendGentleReminderCallable] FCM failed for token ${tokens[i]}:`, result.reason);
            }
        });
    }
    console.log(`[sendGentleReminderCallable] reminder sent from ${callerId} to ${partnerId} in couple ${coupleId}`);
    return { sent: true };
});
//# sourceMappingURL=sendGentleReminderCallable.js.map