import { query } from "./db.js";
const MAX_REASON_CHARS = 300;
// One row per app and category, holding the newest reason and how many times the pair has
// failed. Kept beside send_counters rather than inside it: a counter is one integer per
// outcome per day, and a reason is neither summable nor daily.
export async function recordSendFailure(appId, category, reason) {
    try {
        await query(`INSERT INTO send_failures (app_id, category, reason)
       VALUES ($1, $2, $3)
       ON CONFLICT (app_id, category) DO UPDATE SET
         reason = EXCLUDED.reason,
         failures = send_failures.failures + 1,
         last_at = now()`, [appId, category, reason.slice(0, MAX_REASON_CHARS)]);
    }
    catch (err) {
        console.error("[notify] failure record failed", err);
    }
}
export async function readSendFailures(appIdCategories) {
    if (appIdCategories.length === 0)
        return new Map();
    const res = await query(`SELECT app_id, category, reason, failures, first_at, last_at FROM send_failures
      WHERE app_id || ':' || category = ANY($1::text[])`, [appIdCategories]);
    return new Map(res.rows.map((row) => [`${row.app_id}:${row.category}`, row]));
}
// Same 90 days as the counters: a reason that outlives the counter it explains is as useless
// as the counter that outlived its reason.
export async function pruneSendFailures() {
    try {
        await query(`DELETE FROM send_failures WHERE last_at < now() - interval '90 days'`);
    }
    catch (err) {
        console.error("[notify] failure prune failed", err);
    }
}
