# api.py

from flask import Blueprint, jsonify, request

# 定義一個 Blueprint 物件
api = Blueprint('api', __name__)

# 模擬一些資料
users_data = {
    123: {"id": 123, "name": "Alice", "email": "alice@example.com"},
    456: {"id": 456, "name": "Bob", "email": "bob@example.com"},
    789: {"id": 789, "name": "Charlie", "email": "charlie@example.com"}
}

# 定義 /api/users 路由，回傳所有使用者資料
@api.route('/api/users', methods=['GET'])
def get_all_users():
    return jsonify({
        "status": "success",
        "message": "All users data retrieved successfully.",
        "data": list(users_data.values())
    }), 200

# 定義 /api/users/<id> 路由，回傳指定使用者 ID 的資料
@api.route('/api/users/<int:user_id>', methods=['GET'])
def get_user_by_id(user_id):
    user_info = users_data.get(user_id)
    if user_info:
        return jsonify({
            "status": "success",
            "message": f"User {user_id} found.",
            "data": user_info
        }), 200
    else:
        return jsonify({
            "status": "error",
            "message": f"User {user_id} not found."
        }), 404

# 定義 /api/posts 路由，回傳所有文章資料（模擬）
@api.route('/api/posts', methods=['GET'])
def get_all_posts():
    posts_data = [
        {"id": 101, "title": "First Post", "content": "This is the first post."},
        {"id": 102, "title": "Second Post", "content": "This is the second post."}
    ]
    return jsonify({
        "status": "success",
        "message": "All posts data retrieved successfully.",
        "data": posts_data
    }), 200

# 定義 /api/posts/<id> 路由，回傳指定文章 ID 的資料
@api.route('/api/posts/<int:post_id>', methods=['GET'])
def get_post_by_id(post_id):
    posts_data = {
        101: {"id": 101, "title": "First Post", "content": "This is the first post."},
        102: {"id": 102, "title": "Second Post", "content": "This is the second post."}
    }
    post_info = posts_data.get(post_id)
    if post_info:
        return jsonify({
            "status": "success",
            "message": f"Post {post_id} found.",
            "data": post_info
        }), 200
    else:
        return jsonify({
            "status": "error",
            "message": f"Post {post_id} not found."
        }), 404

# 其他未定義的 API 路徑處理
@api.route('/api/<path:any_path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def handle_undefined_api(any_path):
    return jsonify({
        "status": "error",
        "message": f"API path '{any_path}' is not defined."
    }), 404
