// Task Team — Outgoing Webhooks — notify external systems
async function webhooksFeature(app) {
    await app.db.query(`
        CREATE TABLE IF NOT EXISTS webhook_endpoints (
            id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
            user_id UUID REFERENCES users(id) ON DELETE CASCADE,
            url TEXT NOT NULL,
            events TEXT[] DEFAULT '{"task.created","task.completed"}',
            secret VARCHAR(64),
            active BOOLEAN DEFAULT true,
            created_at TIMESTAMPTZ DEFAULT NOW()
        )
    `).catch(() => {});

    app.get("/webhooks", async (req) => {
        const { user_id } = req.query;
        const { rows } = await app.db.query("SELECT id,url,events,active,created_at FROM webhook_endpoints WHERE user_id=$1", [user_id]);
        return { data: rows };
    });

    app.post("/webhooks", async (req) => {
        const { user_id, url, events, secret } = req.body;
        const crypto = require("crypto");
        const { rows } = await app.db.query(
            "INSERT INTO webhook_endpoints (user_id, url, events, secret) VALUES ($1,$2,$3,$4) RETURNING *",
            [user_id, url, events || ["task.created","task.completed"], secret || crypto.randomBytes(16).toString("hex")]
        );
        return { data: rows[0] };
    });

    app.delete("/webhooks/:id", async (req) => {
        await app.db.query("DELETE FROM webhook_endpoints WHERE id=$1", [req.params.id]);
        return { status: "deleted" };
    });

    // Fire webhook (internal — called from task routes)
    app.post("/webhooks/fire", async (req) => {
        const { event, payload, user_id } = req.body;
        const { rows } = await app.db.query(
            "SELECT * FROM webhook_endpoints WHERE user_id=$1 AND active=true AND $2=ANY(events)",
            [user_id, event]
        );
        let sent = 0;
        for (const wh of rows) {
            try {
                await fetch(wh.url, {
                    method: "POST",
                    headers: { "Content-Type": "application/json", "X-Webhook-Secret": wh.secret || "" },
                    body: JSON.stringify({ event, payload, timestamp: new Date().toISOString() })
                });
                sent++;
            } catch {}
        }
        return { status: "ok", sent, total: rows.length };
    });
}
module.exports = webhooksFeature;
