// Task Team — Notification Preferences — 2026-03-30
async function notifPrefRoutes(app) {
    app.db.query(`
        CREATE TABLE IF NOT EXISTS notification_prefs (
            id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
            user_id UUID REFERENCES users(id) ON DELETE CASCADE,
            task_id UUID REFERENCES tasks(id) ON DELETE CASCADE,
            remind_before_minutes INTEGER DEFAULT 15,
            remind_on_due BOOLEAN DEFAULT true,
            remind_daily BOOLEAN DEFAULT false,
            channels JSONB DEFAULT '["push"]',
            created_at TIMESTAMPTZ DEFAULT NOW(),
            UNIQUE(user_id, task_id)
        )
    `).catch(() => {});

    app.get("/notification-prefs/:taskId", async (req) => {
        const { user_id } = req.query;
        const { rows } = await app.db.query(
            "SELECT * FROM notification_prefs WHERE task_id=$1 AND user_id=$2", [req.params.taskId, user_id]);
        return { data: rows[0] || { remind_before_minutes: 15, remind_on_due: true, remind_daily: false, channels: ["push"] } };
    });

    app.put("/notification-prefs/:taskId", async (req) => {
        const { user_id, remind_before_minutes, remind_on_due, remind_daily, channels } = req.body;
        const { rows } = await app.db.query(
            `INSERT INTO notification_prefs (user_id, task_id, remind_before_minutes, remind_on_due, remind_daily, channels)
             VALUES ($1,$2,$3,$4,$5,$6)
             ON CONFLICT (user_id, task_id) DO UPDATE SET
                remind_before_minutes=EXCLUDED.remind_before_minutes,
                remind_on_due=EXCLUDED.remind_on_due,
                remind_daily=EXCLUDED.remind_daily,
                channels=EXCLUDED.channels
             RETURNING *`,
            [user_id, req.params.taskId, remind_before_minutes || 15, remind_on_due !== false, remind_daily || false, JSON.stringify(channels || ["push"])]);
        return { data: rows[0] };
    });
}
module.exports = notifPrefRoutes;
