// Task Team — Task Templates — predefined task sets
async function templatesFeature(app) {
    await app.db.query(`
        CREATE TABLE IF NOT EXISTS task_templates (
            id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
            name VARCHAR(255) NOT NULL,
            description TEXT DEFAULT '',
            category VARCHAR(50),
            tasks JSONB NOT NULL DEFAULT '[]',
            created_by UUID,
            is_public BOOLEAN DEFAULT true,
            created_at TIMESTAMPTZ DEFAULT NOW()
        )
    `).catch(() => {});

    // List templates
    app.get("/templates", async (req) => {
        const { rows } = await app.db.query("SELECT * FROM task_templates WHERE is_public=true ORDER BY name");
        return { data: rows };
    });

    // Create template
    app.post("/templates", async (req) => {
        const { name, description, category, tasks, created_by } = req.body;
        const { rows } = await app.db.query(
            "INSERT INTO task_templates (name, description, category, tasks, created_by) VALUES ($1,$2,$3,$4,$5) RETURNING *",
            [name, description || "", category || "general", JSON.stringify(tasks || []), created_by]
        );
        return { data: rows[0] };
    });

    // Apply template (creates tasks from template)
    app.post("/templates/:id/apply", async (req) => {
        const { user_id, group_id } = req.body;
        const { rows: templates } = await app.db.query("SELECT * FROM task_templates WHERE id=$1", [req.params.id]);
        if (!templates.length) throw { statusCode: 404, message: "Template not found" };

        const taskList = templates[0].tasks;
        let created = 0;
        for (const t of taskList) {
            await app.db.query(
                "INSERT INTO tasks (title, description, user_id, group_id, priority, status) VALUES ($1,$2,$3,$4,$5,$6)",
                [t.title, t.description || "", user_id, group_id, t.priority || "medium", "pending"]
            );
            created++;
        }
        return { status: "ok", created, template: templates[0].name };
    });

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

    // Seed default templates
    const { rows: existing } = await app.db.query("SELECT count(*) as c FROM task_templates");
    if (parseInt(existing[0].c) === 0) {
        const defaults = [
            { name: "Weekly Sprint", category: "work", tasks: [
                { title: "Sprint planning", priority: "high" },
                { title: "Daily standup notes", priority: "medium" },
                { title: "Code review", priority: "high" },
                { title: "Sprint retrospective", priority: "medium" }
            ]},
            { name: "Study Plan", category: "study", tasks: [
                { title: "Read chapter", priority: "medium" },
                { title: "Take notes", priority: "medium" },
                { title: "Practice exercises", priority: "high" },
                { title: "Review flashcards", priority: "low" },
                { title: "Weekly quiz", priority: "high" }
            ]},
            { name: "Moving Checklist", category: "personal", tasks: [
                { title: "Pack kitchen", priority: "high" },
                { title: "Notify utilities", priority: "high" },
                { title: "Change address", priority: "medium" },
                { title: "Clean old place", priority: "medium" },
                { title: "Unpack essentials", priority: "high" }
            ]}
        ];
        for (const t of defaults) {
            await app.db.query("INSERT INTO task_templates (name, category, tasks) VALUES ($1,$2,$3)",
                [t.name, t.category, JSON.stringify(t.tasks)]);
        }
    }
}
module.exports = templatesFeature;
