// Task Team — Projects CRUD — 2026-03-29
async function projectRoutes(app) {

    // List projects (optionally filter by member)
    app.get("/projects", async (req) => {
        const { user_id } = req.query;
        let query = "SELECT * FROM projects";
        const params = [];
        if (user_id) {
            params.push(user_id);
            query += ` WHERE owner_id = $1 OR $1 = ANY(members)`;
        }
        query += " ORDER BY updated_at DESC";
        const { rows } = await app.db.query(query, params);
        return { data: rows };
    });

    // Get single project with task count
    app.get("/projects/:id", async (req) => {
        const { rows } = await app.db.query(
            `SELECT p.*, 
                (SELECT COUNT(*) FROM tasks t WHERE t.project_id = p.id) as task_count,
                (SELECT COUNT(*) FROM tasks t WHERE t.project_id = p.id AND t.status IN ('done','completed')) as done_count
             FROM projects p WHERE p.id = $1`,
            [req.params.id]
        );
        if (!rows.length) throw { statusCode: 404, message: "Project not found" };
        return { data: rows[0] };
    });

    // Create project
    app.post("/projects", async (req) => {
        const { name, description, color, icon, owner_id } = req.body;
        if (!name || !name.trim()) throw { statusCode: 400, message: "name is required" };
        const { rows } = await app.db.query(
            `INSERT INTO projects (name, description, color, icon, owner_id, members)
             VALUES ($1, $2, $3, $4, $5, ARRAY[$5]::uuid[]) RETURNING *`,
            [name.trim(), description || "", color || "#3B82F6", icon || "\ud83d\udcc1", owner_id]
        );
        return { data: rows[0] };
    });

    // Update project
    app.put("/projects/:id", async (req) => {
        const { name, description, color, icon } = req.body;
        const { rows } = await app.db.query(
            `UPDATE projects SET 
                name = COALESCE($1, name),
                description = COALESCE($2, description),
                color = COALESCE($3, color),
                icon = COALESCE($4, icon),
                updated_at = NOW()
             WHERE id = $5 RETURNING *`,
            [name, description, color, icon, req.params.id]
        );
        if (!rows.length) throw { statusCode: 404, message: "Project not found" };
        return { data: rows[0] };
    });

    // Invite user to project
    app.post("/projects/:id/invite", async (req) => {
        const { user_id } = req.body;
        if (!user_id) throw { statusCode: 400, message: "user_id is required" };
        const { rows } = await app.db.query(
            `UPDATE projects SET 
                members = array_append(members, $1::uuid),
                updated_at = NOW()
             WHERE id = $2 AND NOT ($1::uuid = ANY(members))
             RETURNING *`,
            [user_id, req.params.id]
        );
        if (!rows.length) {
            // Check if project exists
            const check = await app.db.query("SELECT id FROM projects WHERE id = $1", [req.params.id]);
            if (!check.rows.length) throw { statusCode: 404, message: "Project not found" };
            return { status: "already_member" };
        }
        return { data: rows[0], status: "invited" };
    });

    // Remove member from project
    app.delete("/projects/:id/members/:userId", async (req) => {
        const { rows } = await app.db.query(
            `UPDATE projects SET 
                members = array_remove(members, $1::uuid),
                updated_at = NOW()
             WHERE id = $2 RETURNING *`,
            [req.params.userId, req.params.id]
        );
        if (!rows.length) throw { statusCode: 404, message: "Project not found" };
        return { data: rows[0], status: "removed" };
    });

    // Delete project (sets tasks.project_id to NULL via ON DELETE SET NULL)
    app.delete("/projects/:id", async (req) => {
        const { rowCount } = await app.db.query("DELETE FROM projects WHERE id = $1", [req.params.id]);
        if (!rowCount) throw { statusCode: 404, message: "Project not found" };
        return { status: "deleted" };
    });

    // List tasks in project
    app.get("/projects/:id/tasks", async (req) => {
        const { rows } = await app.db.query(
            `SELECT t.*, tg.name as group_name, 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 t.project_id = $1
             ORDER BY t.priority DESC, t.created_at DESC`,
            [req.params.id]
        );
        return { data: rows };
    });
}

module.exports = projectRoutes;
