// Task Team — Gamification — points, streaks, badges
async function gamificationFeature(app) {
    await app.db.query(`
        CREATE TABLE IF NOT EXISTS user_stats (
            user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
            points INTEGER DEFAULT 0,
            level INTEGER DEFAULT 1,
            streak_days INTEGER DEFAULT 0,
            longest_streak INTEGER DEFAULT 0,
            tasks_completed INTEGER DEFAULT 0,
            last_active DATE DEFAULT CURRENT_DATE,
            badges JSONB DEFAULT '[]'
        );
    `).catch(() => {});

    // Get user stats
    app.get("/gamification/stats/:userId", async (req) => {
        let { rows } = await app.db.query("SELECT * FROM user_stats WHERE user_id=$1", [req.params.userId]);
        if (!rows.length) {
            await app.db.query("INSERT INTO user_stats (user_id) VALUES ($1) ON CONFLICT DO NOTHING", [req.params.userId]);
            rows = (await app.db.query("SELECT * FROM user_stats WHERE user_id=$1", [req.params.userId])).rows;
        }
        const stats = rows[0];
        stats.next_level_points = stats.level * 100;
        stats.progress_pct = Math.min(100, Math.round((stats.points % (stats.level * 100)) / (stats.level * 100) * 100));
        return { data: stats };
    });

    // Award points (called internally when task completed)
    app.post("/gamification/award", async (req) => {
        const { user_id, points, reason } = req.body;
        const { rows } = await app.db.query(`
            INSERT INTO user_stats (user_id, points, tasks_completed, last_active)
            VALUES ($1, $2, 1, CURRENT_DATE)
            ON CONFLICT (user_id) DO UPDATE SET
                points = user_stats.points + $2,
                tasks_completed = user_stats.tasks_completed + 1,
                streak_days = CASE
                    WHEN user_stats.last_active = CURRENT_DATE - 1 THEN user_stats.streak_days + 1
                    WHEN user_stats.last_active = CURRENT_DATE THEN user_stats.streak_days
                    ELSE 1
                END,
                longest_streak = GREATEST(user_stats.longest_streak,
                    CASE WHEN user_stats.last_active = CURRENT_DATE - 1 THEN user_stats.streak_days + 1 ELSE 1 END),
                level = 1 + (user_stats.points + $2) / 100,
                last_active = CURRENT_DATE
            RETURNING *
        `, [user_id, points || 10]);
        return { data: rows[0] };
    });

    // Leaderboard
    app.get("/gamification/leaderboard", async (req) => {
        const { rows } = await app.db.query(
            "SELECT us.*, u.name, u.avatar_url FROM user_stats us JOIN users u ON us.user_id=u.id ORDER BY us.points DESC LIMIT 20"
        );
        return { data: rows };
    });

    // Badges
    app.get("/gamification/badges", async () => {
        return { data: [
            { id: "first_task", name: "First Task", icon: "target", description: "Completed first task" },
            { id: "streak_7", name: "7 Day Streak", icon: "fire", description: "7 consecutive days active" },
            { id: "streak_30", name: "30 Day Streak", icon: "diamond", description: "30 consecutive days active" },
            { id: "collaborator", name: "Team Player", icon: "handshake", description: "Collaborated on 5+ tasks" },
            { id: "goal_master", name: "Goal Master", icon: "trophy", description: "Completed 3 goals" },
            { id: "speed_demon", name: "Speed Demon", icon: "lightning", description: "Completed 5 tasks in one day" },
            { id: "polyglot", name: "Polyglot", icon: "globe", description: "Used 3+ languages" }
        ]};
    });
}
module.exports = gamificationFeature;
