// Task Team — Kanban Board — drag-and-drop columns
async function kanbanFeature(app) {
    // Kanban uses existing tasks table, just provides board-view endpoints

    app.get("/kanban/board", async (req) => {
        const { group_id, project_id } = req.query;
        let where = "1=1";
        const params = [];
        if (group_id) { params.push(group_id); where += ` AND t.group_id=$${params.length}`; }
        if (project_id) { params.push(project_id); where += ` AND t.project_id=$${params.length}`; }

        const columns = ["pending", "in_progress", "done", "cancelled"];
        const board = {};
        for (const col of columns) {
            const colParams = [...params, col];
            const { rows } = await app.db.query(
                `SELECT t.id, t.title, t.priority, t.assigned_to, t.group_id, tg.color as group_color, tg.icon as group_icon
                 FROM tasks t LEFT JOIN task_groups tg ON t.group_id=tg.id
                 WHERE ${where} AND t.status=$${colParams.length}
                 ORDER BY t.created_at DESC LIMIT 50`, colParams
            );
            board[col] = rows;
        }
        return { data: board };
    });

    // Move task between columns (change status)
    app.post("/kanban/move", async (req) => {
        const { task_id, new_status } = req.body;
        const valid = ["pending", "in_progress", "done", "completed", "cancelled"];
        if (!valid.includes(new_status)) throw { statusCode: 400, message: "Invalid status" };

        const sets = ["status=$1", "updated_at=NOW()"];
        const params = [new_status];
        if (new_status === "done" || new_status === "completed") sets.push("completed_at=NOW()");
        params.push(task_id);

        const { rows } = await app.db.query(
            `UPDATE tasks SET ${sets.join(",")} WHERE id=$${params.length} RETURNING *`, params
        );
        return { data: rows[0] };
    });
}
module.exports = kanbanFeature;
