# endpoints/members.py
from flask import Blueprint, request, jsonify
from app import get_driver, neo4j_logger

bp = Blueprint('members', __name__)

@bp.route('/members', methods=['GET', 'POST'])
def members():
    if request.method == 'GET':
        return get_persons()
    elif request.method == 'POST':
        return create_person()

def get_persons():
    driver = get_driver()
    with driver.session() as session:
        query = "MATCH (n:Person) RETURN n"
        neo4j_logger.info(f"Executing query: {query}")
        nodes = session.run(query)

        # Convert the nodes to a list of dictionaries
        persons_list = [
            {
                'id': record['n'].id,
                'labels': list(record['n'].labels),
                **{key: value for key, value in record['n'].items()}
            }
            for record in nodes
        ]

    return jsonify({"persons": persons_list})

def create_person():
    data = request.get_json()
    if not data:
        return jsonify({"error": "No data provided"}), 400

    properties = ', '.join([f'{key}: "${key}"' for key in data])
    query = f"CREATE (n:Person {{{properties}}}) RETURN n"

    driver = get_driver()
    with driver.session() as session:
        neo4j_logger.info(f"Executing query: {query} with data: {data}")
        result = session.run(query, **data)

        # Convert the created node to a dictionary
        person = {
            'id': result.single()['n'].id,
            'labels': list(result.single()['n'].labels),
            **{key: value for key, value in result.single()['n'].items()}
        }

    return jsonify(person), 201
