// Task Team — Family Workspace — 2026-03-30
async function familyRoutes(app) {
    await app.db.query(`
        CREATE TABLE IF NOT EXISTS families (
            id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
            name VARCHAR(255) NOT NULL,
            owner_id UUID REFERENCES users(id),
            members UUID[] DEFAULT '{}',
            settings JSONB DEFAULT '{}',
            created_at TIMESTAMPTZ DEFAULT NOW()
        )
    `).catch(() => {});

    app.get("/families", async (req) => {
        const { user_id } = req.query;
        const { rows } = await app.db.query(
            "SELECT * FROM families WHERE owner_id=$1 OR $1=ANY(members)", [user_id]);
        return { data: rows };
    });

    app.post("/families", async (req) => {
        const { name, owner_id } = req.body;
        const { rows } = await app.db.query(
            "INSERT INTO families (name, owner_id, members) VALUES ($1,$2,ARRAY[$2]::uuid[]) RETURNING *",
            [name, owner_id]);
        return { data: rows[0] };
    });

    app.post("/families/:id/members", async (req) => {
        const { user_id } = req.body;
        const { rows } = await app.db.query(
            "UPDATE families SET members=array_append(members,$1::uuid) WHERE id=$2 RETURNING *",
            [user_id, req.params.id]);
        return { data: rows[0] };
    });

    app.get("/families/:id/tasks", async (req) => {
        const { rows: fam } = await app.db.query("SELECT members FROM families WHERE id=$1", [req.params.id]);
        if (!fam.length) throw { statusCode: 404, message: "Family not found" };
        const { rows } = await app.db.query(
            "SELECT t.*, u.name as creator_name FROM tasks t LEFT JOIN users u ON t.user_id=u.id WHERE t.user_id=ANY($1) ORDER BY t.created_at DESC",
            [fam[0].members]);
        return { data: rows };
    });

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

module.exports = familyRoutes;
