from "../lib/common.ry" import users, posts, follows, counters, count_items, text_or_empty, number_or_zero, api_error, request_input, username_key, follow_key, counter_key, post_key, find_user, current_user_doc, active_viewer_username, next_sequence, is_username_char, is_valid_username, is_valid_password, is_valid_bio, is_valid_post_body, user_brief_from_doc, public_user_from_doc, serialize_post_doc, insert_post_desc, sort_posts_desc, collect_posts, discover_posts, user_posts, home_feed_posts

fn register(app)
    @app.get("/api/users/<username>")
    fn get_profile(username)
        user = find_user(username)
        if (user == None)
            return api_error(404, "User not found")

        viewer_username = active_viewer_username()
        return app.json({
            "profile": public_user_from_doc(user, viewer_username),
            "posts": user_posts(username)
        })

    @app.post("/api/users/<username>/follow")
    fn follow_user(username)
        user = current_user_doc()
        if (user == None)
            return api_error(401, "Log in to follow users")

        viewer_username = text_or_empty(user["username"])
        if (viewer_username == username)
            return api_error(400, "You cannot follow yourself")

        target_user = find_user(username)
        if (target_user == None)
            return api_error(404, "User not found")

        relation_id = follow_key(viewer_username, username)
        existing = follows.find_one({"_id": relation_id})
        if (existing != None)
            return api_error(409, "You already follow that user")

        created = follows.insert_one({
            "_id": relation_id,
            "follower_username": viewer_username,
            "following_username": username,
            "created_seq": next_sequence("follows")
        })
        str(created["inserted_id"])

        return app.json({
            "ok": True,
            "profile": public_user_from_doc(target_user, viewer_username)
        })

    @app.post("/api/users/<username>/unfollow")
    fn unfollow_user(username)
        user = current_user_doc()
        if (user == None)
            return api_error(401, "Log in to unfollow users")

        viewer_username = text_or_empty(user["username"])
        if (viewer_username == username)
            return api_error(400, "You cannot unfollow yourself")

        target_user = find_user(username)
        if (target_user == None)
            return api_error(404, "User not found")

        relation_id = follow_key(viewer_username, username)
        existing = follows.find_one({"_id": relation_id})
        if (existing == None)
            return api_error(404, "You do not follow that user")

        deleted = follows.delete_one({"_id": relation_id})
        number_or_zero(deleted)

        return app.json({
            "ok": True,
            "profile": public_user_from_doc(target_user, viewer_username)
        })
